我正在尝试使用以下雄辩查询获取位置的库存值。它正确地提取除了返回null的库存值之外的所有内容(位置名称,地址,用户数量等)。我首先在SQL中构建了这个查询,但是无论出于何种原因都不能在eloquent中工作。这是完全相同的查询。
$locations = \App\Models\Location::select(DB::raw('locations.*', 'SUM(inventory.part_price * inventory.quantity) AS inventory_value'))
->leftJoin('inventory', 'locations.id', '=', 'inventory.location_id')
->where('locations.company_id', '=', Auth::user()->company_id)
->groupBy('locations.id')
->get();
在刀片文件上,我正在使用@foreach
循环。我尝试使用返回null的{{$location->inventory_value}}
。我试图在控制器中转储该特定变量,它也是null。刀片文件如下所示:
它应该返回以下所有的库存值:
最后我的问题是如何修复此查询以获取要在刀片文件上显示的库存价格和数量的总和?谢谢!
使用DB::raw
时,将所有列作为第一个参数(在同一引号内)传递,如:
DB::raw('locations.*, SUM(inventory.part_price * inventory.quantity) AS inventory_value')
您还可以使用selectRaw
使其看起来更清洁,如:
use App\Models\Location;
$locations = Location::selectRaw('locations.*, SUM(inventory.part_price * inventory.quantity) AS inventory_value')->leftJoin...