2

I'm wondering how I can sum the attributes of a multiply-nested relation in Laravel. I'm aware that Laravel has some cool sum functions as shown here, but wondering how to take that one level deeper.

My models are set up as follows:

Projects have many tasks.

Tasks have many logs.

Logs have an attribute "duration."

I've queried projects and are iterating through projects in an html table. I want to display the sum of the log durations. I was thinking maybe I could do something like:

$project->tasks->logs->sum('duration')

But that doesn't do it. Is this possible to do with a single, elegant line like this, or am I going to have to set up a loop and sum "manually"?

Community
  • 1
  • 1
timmyc
  • 512
  • 1
  • 7
  • 16

1 Answers1

10

From your question I assume you have a chain of hasMany relations, so nothing easier:

// Project model
public function logs()
{
  return $this->hasManyThrough('Log', 'Task');
  // defaults to:
  // return $this->hasManyThrough('Log', 'Task', 'project_id', 'task_id');
}

// then sum on the query
$project->logs()->sum('duration');

// or on the collection, but don't do it unless you really need that collection
$project->logs->sum('duration');

You can see the default foreign keys that Eloquent will look for on the models, so adjust them if you don't stick to the Laravel convention.

Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
  • i'm looking for the same result, but i have a deeper chain of relations: is there a way to "build" the sum (i also need to put some `where` conditions trough the relations to filer unwanted rows) without creatin a `HasManyRotugh` ad-hoc relation? – fudo Dec 23 '20 at 14:51