与4张桌子的关系[Laravel 5]

时间:2015-08-05 14:41:44

标签: php mysql laravel-5 eloquent relationships

我有4张桌子:

projects: id, text
comments: id, text
comment_project: project_id, comment_id
project_group: project_id, user_id

我的目标是获取某些项目的所有纪念和用户详细信息。

目前,我能够获得以下项目的所有评论:

class Project extends Model {

    public function comments(){
        return $this->belongsToMany('App\Comment','comment_project');
    }
}

在控制器中我喜欢这样:

$comments = Project::find(1)->comments()->get();
        return $comments;

如果project_id表格中存在user_idproject_group,是否知道如何仅为所选项目提供评论和用户详细信息?

2 个答案:

答案 0 :(得分:2)

您需要在模型中为project_group设置另一种关系方法,然后您应该能够这样做:

$comments = Project::with(['comments','project_group'])
    ->whereHas('project_group',function($q){
        $q->whereNotNull('user_id');
        $q->whereNotNull('project_id');
    });

dd($comments);

型号:

class Project extends Model {

public function comments(){
    return $this->hasMany('App\Comment','comment_project');
}


public function project_group(){
    return $this->hasMany('App\project_group','comment_project'); // < make sure this is the name of your model!
  }

}

试试这个:

$comments = Project::whereHas('groups',function($q){
         $q->where('project_id',1);
     })->whereHas('comments', function($q){
         $q->where('user_id',Auth::id())->where('project_id',1);
     })
     ->get();

return $comments;

答案 1 :(得分:0)

以下是我如何做到这一点,如果有人有更好的想法请评论......

这两种方法都是belongToMany()

$userCondition = function($q){
                        $q->where('user_id',Auth::id())->where('project_id',1);
                    };

             $commentsCondition = function($q){
                        $q->where('project_id',1);
                    };
             $comments = Project::with(['comments' => $commentsCondition,'groups' => $userCondition])
                        ->whereHas('groups', $userCondition)
                        ->whereHas('comments', $commentsCondition)
                        ->get();
        return $comments;