eloquent-2

Previously we dealt with simple relations defined in Eloquent models and eager loading them in order to save database queries.

Now imagine nested relations like this:

So there are one-to-many relations between posts & categories as well as comments & posts.

Above relations look like this:

 

Now, imagine you would like to list all comments for given category.

Naturally we won’t loop through all posts related to the category, as it would be inefficient (n+1 problem), so consider 2 possible solutions:

  1. Load far relation (comments) based on close relation (posts) = nested relationship
  2. Load far relation only (comments) without close (posts)

What you want to do depends on whether you want or not loading posts too.

Here’s how to achieve no. 1 …

… and what Eloquent does behind the scenes:

 

As you can see we ‘ve got lot of data here with only 3 queries. Pretty neat.

But sometimes you don’t really want to load that much. If that’s the case and you only need comments related to the category through posts, then we can do this:

 

So we can accomplish our goal as easily as:

This way we did not load posts, but saved a bit on the queries:

 

Again Eloquent in action is quite impressive and soo easy to work with, ain’t it?!

Above examples could be forked to load only active comments for example.  How? Anyone?

It's only fair to share...Tweet about this on TwitterShare on RedditPin on PinterestShare on FacebookShare on Google+

Related Post

Querying relations with Eloquent in Laravel 4 Laravel ORM Eloquent is brilliant! That being said, let's try to tackle very common questions that appear when you try to get related models lo...
Querying relations in Laravel: get Models where la... Another part of Querying relations in Laravel will cover such problem: I want to get SomeModels that have latest RelatedModel (hasMany) matchin...
Laravel – querying any level far relations w... Eloquent provides one Relation type for far related tables - hasManyThrough. However it works only with with cascade of hasOne/hasMany relations a...
Laravel – how to define and use Eloquent Glo... Laravel 4.2 introduced a new way of handling soft deletes by making use of traits and query builder macros wrapped in as a feature, that many people a...