Skip to content

Commit

Permalink
[8.x] Document MorphTo relationship eager loading constraints (#6569)
Browse files Browse the repository at this point in the history
* MorphTo relationship eager loading constraints

Re: laravel/framework#35190

* Update eloquent-relationships.md

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
tobyzerner and taylorotwell committed Nov 13, 2020
1 parent 9465d12 commit 0ac7add
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions eloquent-relationships.md
Expand Up @@ -1313,6 +1313,27 @@ In this example, Eloquent will only eager load posts where the post's `title` co

> {note} The `limit` and `take` query builder methods may not be used when constraining eager loads.
<a name="constraining-eager-loading-of-morph-to-relationships"></a>
#### Constraining Eager Loading Of `MorphTo` Relationships

If you are eager loading a `MorphTo` relationship, Eloquent will run multiple queries to fetch each different type of related model. You may target conditions to each of these queries using the `MorphTo` relation's `constrain` method:

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

$comments = Comment::with(['commentable' => function (MorphTo $morphTo) {
$morphTo->constrain([
Post::class => function (Builder $query) {
$query->whereNull('hidden_at');
},
Video::class => function (Builder $query) {
$query->where('type', 'educational');
},
]);
}])->get();

In this example, Eloquent will only eager load posts that have not been hidden and videos have a `type` value of "educational".

<a name="lazy-eager-loading"></a>
### Lazy Eager Loading

Expand Down

0 comments on commit 0ac7add

Please sign in to comment.