Laravel 4.1 Eager Loading Nested Relationships with Constraints

后端 未结 3 1734
一整个雨季
一整个雨季 2021-02-08 03:03

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:

<         


        
3条回答
  •  不知归路
    2021-02-08 03:49

    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

提交回复
热议问题