如何在eagerloaded关系Laravel上附加额外的数据

时间:2018-02-05 13:33:34

标签: laravel eager-loading

我有这个功能,可以加载帖子,

public function getUserPosts()
{
    return User::with('posts')->where("organization_id", $this->getOrganization()->id)->get()->toArray();
}

这回复用户的帖子,我的问题是我可以在eagerload上添加一些额外的数据吗

    public function getUserPosts()
    {
        return User::with('posts', function(){

         //say I fetch an array of posts here, 
        // I want to attach this array of posts with the eagerloaded posts 

        })->where("organization_id", $this->getOrganization()->id)->get()->toArray();
    }

1 个答案:

答案 0 :(得分:1)

return User::with(['posts', function($query){
          //here you have the query to the relationship, and can do normal query stuff with it
          //like this:
          $query->with('comments')->select('id', 'title')->where('created_at','>',Carbon::now());

        }])->where("organization_id", $this->getOrganization()->id)->get()->toArray();