I'm trying to optimize this code because it's causing Timeout problems.
It's getting all items from database and performing SUM() in PHP.
public function getInstalledCost()
{
$items = $this->stockItems()
->where('status', 'INSTALADO')
->with(['shipment' => function($q){ $q->select('id', 'item_cost'); }])
->select('id','shipment_id')
->get();
$cost = 0;
foreach($items as $i){
$cost += $i->shipment->item_cost;
}
return $cost;
}
So is there any way to get this data already SUM() from the database?