Laravel How to use hasManyThrough with groupBy?

Viewed 173

is there any way to count a group with a hasManyThrough in Laravel? I have this database:

projects (id, project)
milestones (id, project_id,milestone)
todos (id,milestone_id,todo)

In my todos I am storing a employee. Now I want to know how many employees are working in project.

My Project Model looks like this:

public function employee()
{
    return $this->hasManyThrough('App\Models\Todo', 'App\Models\Milestone');
}

My resource looks like this if I want to see all Todo in my Project:

'employee' => $this->employee()->get(),

How does my resource and/or model have to look like if I want to know how many employee are working in project. I tried something like this (not working):

'employee' => $this->employee()->groupBy('employee')->count(),
2 Answers
  There are multiple ways of getting count of relational table
    Project::with(array('employee' => function($query) {
            $query->groupBy('employee')->count();
        }))
        ->get();
    Another way of getting relational count
    Project::withCount('employee')->get();

If you only has an employee for a todo, just use withCount():

$projects = Project::withCount(['employees' => function (Builder $query) {
    $query->where('employee_id', '!=', null);
}])->get();

And call {relationship}_count to show the result:

foreach($projects as $project) {
   echo $project->employees_count;
}
Related