Firstly I have a "companies" table that has a "has many" relationships with a "purchases" table. The "purchases" has a has a "has many" relationship to an "items" table. On each item I store the cost of that item at the time of purchase. I have a method on my companies "getTotalSpent" which works out how much the company has spent across all purchases. My current method works but I think there is probably a more efficient way.
public function getTotalSpent(): int
{
return $this->purchases()
->with('items')
->get()
->pluck('items')
->flatten()
->unique()
->sum('cost');
}
Any help to optimise this would be appreciated. Thanks
$this->purchases = Purchase->withSum('items as total','cost') ...
// or
Purchase->withSum([
'items' => fn ($q) => $q->distinct(), // not sure you need this?
'cost'
])
...