Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] MorphTo relationship eager loading constraints #35190

Merged
merged 2 commits into from Nov 12, 2020

Conversation

tobyzerner
Copy link
Contributor

@tobyzerner tobyzerner commented Nov 12, 2020

Currently it is not possible to apply different constraints to the queries that eager load each different type in a morph-to relation. You can apply constraints directly to the MorphTo relation object:

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphTo;

$activities = ActivityFeed::query()
    ->with(['parentable' => function (MorphTo $query) {
        $query->where('foo', 'bar');
    }])->get();

However these constraints will be applied uniformly to the queries for each morph type, so it is only useful if constraining by a column which is present on all types – otherwise, it will fail.

In a similar vein to the morphWith method introduced in #28647, this PR introduces the ability to apply different constraints to the queries for each type:

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphTo;

$activities = ActivityFeed::query()
    ->with(['parentable' => function (MorphTo $morphTo) {
        $morphTo->constrain([
            Event::class => function (Builder $query) {
                $query->where('event_foo', 'bar');
            },
            Photo::class => function (Builder $query) {
                $query->where('photo_foo', 'bar');
            },
        ]);
    }])->get();

@taylorotwell
Copy link
Member

Thanks. Could you send a PR to the laravel/docs repository for this?

@taylorotwell taylorotwell merged commit 252872f into laravel:8.x Nov 12, 2020
@tobyzerner
Copy link
Contributor Author

Sure can!

@tobyzerner tobyzerner deleted the morphto-constrain branch November 12, 2020 23:47
taylorotwell added a commit to laravel/docs that referenced this pull request Nov 13, 2020
* MorphTo relationship eager loading constraints

Re: laravel/framework#35190

* Update eloquent-relationships.md

Co-authored-by: Taylor Otwell <taylor@laravel.com>
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.

None yet

3 participants