Skip to content

Commit

Permalink
[11.x] Where doesnt have nullable morph (#54363)
Browse files Browse the repository at this point in the history
* first pass at allowing querying non existence of nullable morph - will need moving up

* move querying non existence of nullable morph to has morph method

* handle checking for 0 has morphs the same as less than 1 has morphs

* work on assumption that has morph less than needs null check

* attempt to handle all operators

* merge into existing query - all existing tests passing

* add test

* revert signature change

* readd docblocks

* fix space

* formatting

---------

Co-authored-by: Mior Muhammad Zaki <[email protected]>
  • Loading branch information
liamduckett and crynobone authored Feb 6, 2025
1 parent d637b4a commit b29fa77
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,12 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole

$types = (array) $types;

$checkMorphNull = $types === ['*']
&& (($operator === '<' && $count >= 1)
|| ($operator === '<=' && $count >= 0)
|| ($operator === '=' && $count === 0)
|| ($operator === '!=' && $count >= 1));

if ($types === ['*']) {
$types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())
->filter()
Expand Down Expand Up @@ -274,7 +280,8 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole
->whereHas($belongsTo, $callback, $operator, $count);
});
}
}, null, null, $boolean);
}, null, null, $boolean)
->when($checkMorphNull, fn (self $query) => $query->orWhereMorphedTo($relation, null));
}

/**
Expand Down
7 changes: 7 additions & 0 deletions tests/Integration/Database/EloquentWhereHasMorphTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,13 @@ public function testModelScopesAreAccessible()

$this->assertEquals([1, 4], $comments->pluck('id')->all());
}

public function testWhereDoesntHaveMorphWithNullableMorph()
{
$comments = Comment::whereDoesntHaveMorph('commentable', '*')->orderBy('id')->get();

$this->assertEquals([3, 7, 8], $comments->pluck('id')->all());
}
}

class Comment extends Model
Expand Down

0 comments on commit b29fa77

Please sign in to comment.