Skip to content

[11.x] Pass collection of models to whereMorphedTo / whereNotMorphedTo#54324

Merged
taylorotwell merged 4 commits into
laravel:11.xfrom
gdebrauwer:where-morphed-to-with-multiple-models
Jan 24, 2025
Merged

[11.x] Pass collection of models to whereMorphedTo / whereNotMorphedTo#54324
taylorotwell merged 4 commits into
laravel:11.xfrom
gdebrauwer:where-morphed-to-with-multiple-models

Conversation

@gdebrauwer

@gdebrauwer gdebrauwer commented Jan 23, 2025

Copy link
Copy Markdown
Contributor

The whereBelongsTo method supports providing a collection of models. This PR adds that behavior to the whereMorphedTo (and whereNotMorphedTo) method

Comment::whereMorphedTo('commentable', $posts)->get();

Comment::whereNotMorphedTo('commentable', $posts)->get();

It also supports providing a collection with different kinds of models:

Comment::whereMorphedTo('commentable', [$post, $video])->get();

Comment::whereNotMorphedTo('commentable', [$post, $video])->get();

@gdebrauwer gdebrauwer marked this pull request as draft January 23, 2025 16:41
@gdebrauwer gdebrauwer marked this pull request as ready for review January 24, 2025 15:57
@taylorotwell taylorotwell merged commit f4043fe into laravel:11.x Jan 24, 2025
$models->groupBy(fn ($model) => $model->getMorphClass())->each(function ($models) use ($query, $relation) {
$query->orWhere(function ($query) use ($relation, $models) {
$query->where($relation->qualifyColumn($relation->getMorphType()), '<=>', $models->first()->getMorphClass())
->whereNotIn($relation->qualifyColumn($relation->getForeignKeyName()), $models->map->getKey());

@owenvoke owenvoke Mar 4, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gdebrauwer, should this be changed to whereIn() as it's negating a negative at the moment? 🤔 We are experiencing issues with whereNotMorphedTo() on upgrading to 11.40.x

Here's a comparison of the differences:

# Previous logic (`<11.40`)
select *
from `posts`
where not (`posts`.`author_type` <=> 'user' and `posts`.`author_id` <=> 1);

# Current logic (`>=11.40`)
select *
from `posts`
where not ((`posts`.`author_type` <=> 'user' and `posts`.`author_id` not in (1)));

# Updated logic (with `whereIn()`), this logic more aligns with the previous logic
select *
from `posts`
where not ((`posts`.`author_type` <=> 'user' and `posts`.`author_id` in (1)));

I've opened a PR here: #54902

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants