I am trying to get Eager-Loading nested relationships, with constraints, to work. Everyone seems to be giving the same example of eager-loading nested relationships:
<
It's hard to achieve that in the context of User->Post->Comment, but you can easily do this starting from Post if that suit you:
Post::with('users')->with('comments')->find(1);
as it will load all users and all comments related to the given post.
-- edit: Don't trust the first sentence, it's as simple as this:
// $id of the post you want
User::with(['comments' => function ($q) { // this is hasManyThrough relation
$q->where('post_id',$id); // comments only related to given post
}])->with(['posts' => function ($q) {
$q->whereId($id); // here we load only the post you want
}])->whereHas('posts', function ($q) {
$q->whereId(1); // here we filter users by the post
})->get();
Mind though that Laravel will run 3 queries to get it done