Vladimir Djukic
Vladimir Djukic

Reputation: 2072

Relations with 4 tables [Laravel 5]

I have 4 tables:

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?

Upvotes: 1

Views: 37

Answers (2)

baao
baao

Reputation: 73251

You'll need to set another relation method for project_group in your Model, then you should be able to get this like so:

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

Upvotes: 2

Vladimir Djukic
Vladimir Djukic

Reputation: 2072

Here is how I do this, if anyone has better idea pls comment...

Both methods are 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;

Upvotes: 0

Related Questions