schu's avatar
Level 1

Eager load sub relationship for filtered parent

I have a relationship Foo -> Bar -> Baz. I want all Foo plus all Bar if the current user is the owner (Bar has a user_id column) plus all Baz for the filtered subset of Bar (where current user is the owner).

Foo::with([
  'bar' => function ($query) { $query->where('user_id', '=', Auth::id()); }
])->get()

would only load Foo with Bar but not include Baz.

Foo::with([
  'bar.baz' => function ($query) { $query->where('user_id', '=', Auth::id()); }
])->get()

wouldn't work, as Baz doesn't have a column user_id to filter on.

What's the best/idiomatic way to filter on Bar and eager load Baz in the same statement?

0 likes
1 reply
schu's avatar
Level 1

Nevermind, adding the with statement to the subquery works:

Foo::with([
  'bar' => function ($query) { $query->where('user_id', '=', Auth::id())->with('baz'); }
])->get()

Please or to participate in this conversation.