Laravel -如何从关系中求和()字段



我正在尝试优化这段代码,因为它会导致超时问题。

它从数据库中获取所有项目并在PHP中执行SUM()。

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;
}

那么是否有任何方法可以从数据库中获得此数据SUM() ?

使用sum()方法可以将Laravel中的集合求和写得更短

$items->sum(function ($item) {
return count($item['item_cost']);
});

为以后做个提示。

要对一个关系的字段求和,你可能会这样做

StockItem::whereHas('shipment', function ($q) use ($shipmentId) {
$q->where('shipment_id', $shipmentId);
})->sum('shipments.item_price');

我假设您已经正确地设置了stockItemsshipments之间的关系,并且在您的StockItem模型上有shipments关系。

最新更新