0

Here is my relation:

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

I am trying to get acount of all comments...

Here is my query

 $count = Project::with(['commentsCount' => function($q) {
                    $q->where('project_id', $this->id);
            }, 'groups' => function($q) {
                $q->where('project_id', $this->id)->where('user_id', Auth::id());
            }])->where('id', $this->id)->get();

Any solution?

Vladimir Djukic
  • 2,042
  • 7
  • 29
  • 60

2 Answers2

0

Try this

$projects = Project::with('commentsCount')->get();

foreach($projects as $project){
    echo $project->commentsCount()->count()
}

OR

public function commentsCount(){
    return $this->belongsToMany('App\Comment','project_comment')->count();
}

$projects = Project::with('commentsCount')->get();

foreach($projects as $project){
    echo $project->commentsCount;
}
Shakti
  • 189
  • 1
  • 3
  • 15
0

I think this will work

 $projects= Project::with('commentsCount','groups') 
         ->where('id', $this->id)->first();
 $comments_count = $projects -> commentsCount -> count();   
mdamia
  • 4,447
  • 1
  • 24
  • 23