Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jlcain3's avatar

Converting collection sum to efficient query

Hello all!

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

0 likes
3 replies

Please or to participate in this conversation.