My tables are: projects -> tasks -> commands
Trying to calculate average on field duration
Project::with('tasks.commands')->withAvg('commands', 'duration')
It can't work because Eloquent expects database field duration
here. But in my case duration
is custom attribute in Command model.
How to use aggregates with custom attributes?
$projects = Project::with('tasks.commands')->get();
$projects->each(function ($project) {
$project->avg_duration = $project->tasks->flatMap->commands->avg('duration');
});
Try this should work