简体   繁体   English

与4个表的关系[Laravel 5]

[英]Relations with 4 tables [Laravel 5]

I have 4 tables: 我有4张桌子:

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

My goal is to take all commets and user details for some project. 我的目标是获取某个项目的所有详细信息和用户详细信息。

Currently I am able to get all comments for projects like this: 目前,我能够获得有关以下项目的所有评论:

class Project extends Model {

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

and in controller I do like this: 在控制器中,我这样做:

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

Any idea how to take only comments and user details for selected project if project_id and user_id exists in project_group table? 如果project_group表中存在project_iduser_id是否知道如何仅获取所选项目的注释和用户详细信息?

You'll need to set another relation method for project_group in your Model, then you should be able to get this like so: 您需要在模型中为project_group设置另一个关联方法,然后应该能够像这样获得该信息:

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

dd($comments);

Model: 模型:

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!
  }

}

Try this: 尝试这个:

$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;

Here is how I do this, if anyone has better idea pls comment... 如果有人有更好的主意请发表评论,这就是我的做法...

Both methods are belongToMany() 这两个方法都属于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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM