Richard
Richard

Reputation: 733

Get table with sum for every employee

I have a table like this:

employee_id
task_hour
month
project_id

I would like to get the sum of hours an employee has worked every month. I tried the following:

$activity = $this->activity
        ->get(['employee_id','month','task_hour'])->sum('task_hour');

But I only get one number. In fact, I would like to see each employee, then each month then the sum of task hours.

Thanks.

Upvotes: 1

Views: 59

Answers (1)

Filip Koblański
Filip Koblański

Reputation: 10018

If You want to use aggregate query in right way, just add a group by like:

$activity = $this->activity
     ->select('employee_id', 'month', DB::raw('SUM(task_hour) as task_hour'))
     ->groupBy('employee_id', 'month')
     ->get();

You'll get a collection with a sum of task hours in every month.

Upvotes: 1

Related Questions