[英]Relations with 4 tables [Laravel 5]
我有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_group
表中存在project_id
和user_id
是否知道如何仅获取所选项目的注释和用户详细信息?
您需要在模型中为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;
如果有人有更好的主意请发表评论,这就是我的做法...
这两个方法都属于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.