Home > Mobile >  Laravel GroupBy with Sum added to Object
Laravel GroupBy with Sum added to Object

Time:09-30

I searched all other questions before. I have to simple groupBy select and get sum out of column. But how to make 1 query out of this ( without merge ). Possible?

$Todo = Todo::selectRaw('sum(estimated_time) as amount')->groupBy('user_name')->get();
$Todo = Todo::get()->groupBy('user_name');

CodePudding user response:

I would suggest you avoid using any raw SQL statements in Laravel.

If your goal is to get the sum of the estimated duration of all todos for each user, you can use eager loading.

For example you could first query all your users and eager load the todos.

$users = User::query()->with('todos')->get();

And then you can retrieve the sum of the estimated duration for all todos.

foreach($users as $user) {
     $user->totalEstimatedTodoTime = $user->todos->sum('estimated_time')
}

If you use the total estimated todo time of a user often. You could even define an accessor

For example in your user model:

public function getTotalEstimatedTodoTimeAttribute() {
 return $this->todos->sum('estimated_time');
}

Then you can retrieve the value like this:

$user->totalEstimatedTodoTime

CodePudding user response:

Write this code in Model :

public function setXXXAttribute($value)
{
     $this->XXX= Model::where('user_name' , $this->user_name)->sum('estimated_time');
}


public function getXXXAttribute($value)
{
     return $this->XXX
}
  • Related