我的模型是这样构造的:
Stock (hasMany) StockItem
StockItem (belongsTo) Shipment
Shipment (hasMany) StockItem
- item_cost = double
因此,我试图获取所有项目及其总费用的总和(位于“装运”模型中)。
public function getStockItemsTotalCost($stockItemId=null){
$q = $this->stockItems()->where('id','=',$stockItemId)->with('shipment')->withCount([
'shipment AS cost_total' => function ($query) {
$query->select(DB::raw("SUM(item_cost) AS cost_total"));
}
]);
print_r($q);exit;
}
这将返回Allowed memory size of 268435456 bytes exhausted
错误。
这是执行此查询的最佳方法吗?
我进步很小
public function getStockItemSumCost($stockItemId){
$q = $this->stockItems()->whereHas('stockPart', function($q) use ($stockItemId) {
return $q->where('id', '=', $stockItemId);
})->with('shipment')
->get();
print_r($q->toArray());exit;
}
这将返回一个StockItem列表,每个列表中都包含Shipment ... 我需要的是一个包含所有Shipment.item_cost列的SUM()的列。
答案 0 :(得分:0)
解决了:
public function getStockItemSumCost($stockItemId){
$q = $this->stockItems()
->whereHas('stockPart', function($q) use ($stockItemId) { return $q->where('id', '=', $stockItemId); })
->join('shipments', 'stock_items.shipment_id', '=', 'shipments.id')
->sum('item_cost');
return $q;
}