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

Php Laravel-如何从关系求和()字段,php,laravel,Php,Laravel,我正在尝试优化此代码,因为它会导致超时问题 它从数据库中获取所有项,并在PHP中执行SUM() 那么,是否有任何方法可以从数据库中获取此数据SUM()?使用 $items->sum(函数($item){ 退货计数($item['item_cost']); }); 作为以后的提示 对关系的一个字段求和,你可能会这样做 StockItem::whereHas('shipping',函数($q)use($shipmentId){ $q->where('shipping_id',$shipmentId

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

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


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

使用

$items->sum(函数($item){
退货计数($item['item_cost']);
});
作为以后的提示

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

StockItem::whereHas('shipping',函数($q)use($shipmentId){
$q->where('shipping_id',$shipmentId);
})->总额(“装运。项目价格”);

我假设您已正确设置了
stockItems
shippings
之间的关系,并且在
StockItem
模型上具有
shippings
关系。

使用

$items->sum(函数($item){
退货计数($item['item_cost']);
});
作为以后的提示

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

StockItem::whereHas('shipping',函数($q)use($shipmentId){
$q->where('shipping_id',$shipmentId);
})->总额(“装运。项目价格”);

我假设您已正确设置了
stockItems
shippings
之间的关系,并且在
StockItem
模型上具有
shippings
关系。

您的第一个提示返回
count():参数必须是实现可计数的数组或对象
您的第二个提示需要
shipmentId
,这不是我的情况。My StockItem类belongsTo()装运类首先,您需要检查$item中的内容,并需要替换为正确的字段。这或多或少是一个示例。您的第一个提示返回
count():参数必须是实现可计数的数组或对象
您的第二个提示需要
shipmentId
,这不是我的情况。My StockItem类belongsTo()装运类首先,您需要检查$item中的内容,并需要替换为正确的字段。这或多或少是一个例子。
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;
}