trick

Eloquent provides one Relation type for far related tables – hasManyThrough. However it works only with with cascade of hasOne/hasMany relations and you can use it only for 2 levels of nesting, while sometimes you need more.

Imagine, that you want to get the posts for logged-in user, having this setup:

Now, because there is no built-in method for such case, you would probably think of getting all the tags, looping through them, and merging all the posts from each tag. While this would work, it would be cumbersome, so let’s make it easier!

First, let’s see what hasManyThrough can do for us:

 

Compared to the User, Tag, Post case, it is so easy. For the latter, we could do this:

 

As you can see it is rather cumbersome and would be really cool, if it could be simplified.

So here’s the trick that you can use for any level of nesting and any type of relation:

 

Woow, it was sooo easy, but wtf is going on there?  you could say :)

So let’s do it again step by step:

There’s one more thing to say here – when we call get in the closure, the query is executed straight away, unlike with eager loading. That being said, the code above calls one additional query: 1 for tags, 1 for posts (eager loading) + 1 for posts, that we called.

And that’s it. Now you can get any far related models with no effort.

Edit: As pointed out by Joseph Silber in the comment, you can handle such case easily with collection methods, like shown below. However, the idea behind the trick here, is that you can use it in this form for no-matter-how-far relation and it will work just the same, and that’s something you couldn’t achieve with collection methods easily.

 

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

Related Post

Tweaking Eloquent relations – how to get N related... Previously I showed you how to get single related model per each parent, while eager loading the hasMany relation. That was pretty easy and we jus...
Tweaking Eloquent relations – how to get lat... Have you ever needed to show only single related model from the hasMany relationship on a set of parents? Being it latest, highest or just rand...
How to store clients in database? That is, Party M... Have you ever been building any app that handled client's data, was it e-commerce, crm or anything similar, you surely wondered, how to store it in ...
Querying relations in Laravel 4: nested relation Previously we dealt with simple relations defined in Eloquent models and eager loading them in order to save database queries. Now imagine nest...