29.07.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Eloquent: Relationships 464<br />

.<br />

10 * Get the author that wrote the book.<br />

11 */<br />

12 public function author()<br />

13 {<br />

14 return $this->belongsTo('App\Author');<br />

15 }<br />

16 }<br />

Now, let’s retrieve all books and their authors:<br />

.<br />

1 $books = App\Book::all();<br />

2<br />

3 foreach ($books as $book) {<br />

4 echo $book->author->name;<br />

5 }<br />

This loop will execute 1 query to retrieve all of the books on the table, then another query for each<br />

book to retrieve the author. So, if we have 25 books, this loop would run 26 queries: 1 for the original<br />

book, and 25 additional queries to retrieve the author of each book.<br />

Thankfully, we can use eager loading to reduce this operation to just 2 queries. When querying, you<br />

may specify which relationships should be eager loaded using the with method:<br />

.<br />

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

2<br />

3 foreach ($books as $book) {<br />

4 echo $book->author->name;<br />

5 }<br />

For this operation, only two queries will be executed:<br />

.<br />

1 select * from books<br />

2<br />

3 select * from authors where id in (1, 2, 3, 4, 5, ...)

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

Saved successfully!

Ooh no, something went wrong!