Skip to content

Commit b29fa77

Browse files
[11.x] Where doesnt have nullable morph (#54363)
* 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]>
1 parent d637b4a commit b29fa77

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,12 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole
244244

245245
$types = (array) $types;
246246

247+
$checkMorphNull = $types === ['*']
248+
&& (($operator === '<' && $count >= 1)
249+
|| ($operator === '<=' && $count >= 0)
250+
|| ($operator === '=' && $count === 0)
251+
|| ($operator === '!=' && $count >= 1));
252+
247253
if ($types === ['*']) {
248254
$types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())
249255
->filter()
@@ -274,7 +280,8 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole
274280
->whereHas($belongsTo, $callback, $operator, $count);
275281
});
276282
}
277-
}, null, null, $boolean);
283+
}, null, null, $boolean)
284+
->when($checkMorphNull, fn (self $query) => $query->orWhereMorphedTo($relation, null));
278285
}
279286

280287
/**

tests/Integration/Database/EloquentWhereHasMorphTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,13 @@ public function testModelScopesAreAccessible()
255255

256256
$this->assertEquals([1, 4], $comments->pluck('id')->all());
257257
}
258+
259+
public function testWhereDoesntHaveMorphWithNullableMorph()
260+
{
261+
$comments = Comment::whereDoesntHaveMorph('commentable', '*')->orderBy('id')->get();
262+
263+
$this->assertEquals([3, 7, 8], $comments->pluck('id')->all());
264+
}
258265
}
259266

260267
class Comment extends Model

0 commit comments

Comments
 (0)