29.07.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Eloquent: Relationships 465<br />

Eager Loading Multiple Relationships<br />

Sometimes you may need to eager load several different relationships in a single operation. To do<br />

so, just pass additional arguments to the with method:<br />

.<br />

1 $books = App\Book::with('author', 'publisher')->get();<br />

Nested Eager Loading<br />

To eager load nested relationships, you may use “dot” syntax. For example, let’s eager load all of the<br />

book’s authors and all of the author’s personal contacts in one Eloquent statement:<br />

.<br />

1 $books = App\Book::with('author.contacts')->get();<br />

Constraining Eager Loads<br />

Sometimes you may wish to eager load a relationship, but also specify additional query constraints<br />

for the eager loading query. Here’s an example:<br />

.<br />

1 $users = App\User::with(['posts' => function ($query) {<br />

2 $query->where('title', 'like', '%first%');<br />

3<br />

4 }])->get();<br />

In this example, Eloquent will only eager load posts that if the post’s title column contains the<br />

word first. Of course, you may call other query builder to further customize the eager loading<br />

operation:<br />

.<br />

1 $users = App\User::with(['posts' => function ($query) {<br />

2 $query->orderBy('created_at', 'desc');<br />

3<br />

4 }])->get();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!