06.10.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 595<br />

Counting Relationship Results<br />

If you want to count the number of results from a relationship without actually loading them you<br />

may use the withCount method, which will place a {relation}_count column on your resulting<br />

models. For example:<br />

1 $posts = App\Post::withCount('comments')->get();<br />

2<br />

3 foreach ($posts as $post) {<br />

4 echo $post->comments_count;<br />

5 }<br />

You may add retrieve the “counts” for multiple relations as well as add constraints to the queries:<br />

1 $posts = Post::withCount(['votes', 'comments' => function ($query) {<br />

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

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

4<br />

5 echo $posts[0]->votes_count;<br />

6 echo $posts[0]->comments_count;<br />

Eager Loading<br />

When accessing Eloquent relationships as properties, the relationship data is “lazy loaded”. This<br />

means the relationship data is not actually loaded until you first access the property. However,<br />

Eloquent can “eager load” relationships at the time you query the parent model. Eager loading<br />

alleviates the N + 1 query problem. To illustrate the N + 1 query problem, consider a Book model<br />

that is related to Author:<br />

1

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

Saved successfully!

Ooh no, something went wrong!