mstarkey's avatar

Sum on multiple columns in a row

I am trying to calculate the total hours spent on a task per day for each task in a list.

this is the current code

$entries = TimesheetEntry::with('project', 'client', 'timesheetTask')
                    ->whereHas('project', function ($q) use ($client_id) {
                        $q->where('client_id', '=', $client_id);
                    })
                    ->whereBetween('updated_at', [$start, $end])
                    ->get();

the query spits out

client, project, task and hours for each day (Monday to Sunday) between 2 dates

I would like to return

client, project, task and total hours for each day (Monday to Sunday) between 2 dates

i.e.

client, project, task, 12(total)

any help would be greatly appreciated.

0 likes
4 replies
mdeorue's avatar

You can do it, in the model side or controller side, for example

Eloquent query builder:

$entries = TimesheetEntry::with('project', 'client', 'timesheetTask')
                    ->whereHas('project', function ($q) use ($client_id) {
                        $q->where('client_id', '=', $client_id);
                    })
                    ->whereBetween('updated_at', [$start, $end])
                    ->selectRaw('client, project, task, sum(hours) as task_hours')
->groupBy('client', 'project', 'task')
->get();

Controller

$entries = TimesheetEntry::with('project', 'client', 'timesheetTask')
                    ->whereHas('project', function ($q) use ($client_id) {
                        $q->where('client_id', '=', $client_id);
                    })
                    ->whereBetween('updated_at', [$start, $end])
                    ->get();
$clientProjectTasks = $entries->groupBy(['client', 'project', 'task']);

And then when you need to show a table with the total hours you can do this.

foreach($clientProjectTasks as $clientProjectTask){
$clientProjectTask->sum('hours);
}

Regards

mstarkey's avatar

how does this take into consideration that there are 7 columns (mon_hrs, tue_hrs) etc...

->selectRaw('client, project, task, sum(hours) as task_hours')
->groupBy('client', 'project', 'task')

thanks

mdeorue's avatar
mdeorue
Best Answer
Level 6

Ow, maybe you can use the same but with the 7 columns

->selectRaw('client, project, task, sum(mon_hrs) as mon_hrs, sum(tue_hrs) as tue_hrs, ...')
->groupBy('client', 'project', 'task')

But if you want to sum everything I will prefer us a Accesor

class TimesheetEntry{

public function getWeekHoursAttribute()
{
    return $this->mon_hrs + $this->tue_hrs + ...;
}

}

Regards

1 like

Please or to participate in this conversation.