Tom
Tom

Reputation: 12998

Joining multiple tables on an already joined table using Eloquent

I have the following which brings back all users in a group along with their posts.

$group = Group::where('id', $id)->with('users.posts')->firstOrFail();

However, what I need is an additional join on the users to bring back additional (hasMany) information.

What I want is something like this (although this doesn't work)

$group = Group::where('id', $id)->with('users.posts,houses')->firstOrFail();

The sql would look something like

SELECT * FROM groups 
JOIN group_users ON groups.id = group_users.group_id
JOIN users ON users.id = group_users.user_id
JOIN posts ON posts.user_id = users.id
JOIN house_users ON house_users.user_id = users.id
JOIN houses ON houses.id = house_users.house_id
WHERE groups.id = 123

Upvotes: 1

Views: 90

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29278

If you pass a single argument to with(), it will look for a relationship with a matching name. Using a single string with a comma won't work as it won't parse and respect it. Since you're trying to use multiple relationships, this needs to be multiple signature, which there are a couple ways to accomplish.

First, array syntax:

->with(["users.posts", "houses"])

Second, multiple arguments:

->with("users.posts", "houses")

Either method will specify that you want multiple relationships loaded to your initial query; preference is given to whichever you find easier to read.

Upvotes: 1

Related Questions