How to aggregate query on related table's field in Laravel?
我的 laravel 5.4 应用程序有一个一对多(反向)关系。有两个模型
1 2 3 4 | public function vehicle() { return $this->belongsTo('App\\Models\\Vehicle','vehicle_id'); } |
表
表
我想要的是搜索条件内
我尝试了一些方法,如下所示:
1 2 3 | $query = Sale::where('status', 1); $query = $query->where('date_time', '<',"2017-05-10 10:10:05"); $totalVolume = $query->whereHas('vehicle')->sum('vehicles.volume'); |
并导致以下错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'vehicles.volume' in 'field list' (SQL: select
sum(vehicles .volume ) as aggregate fromsales wherestatus = 1
anddate_time <"2017-05-10 10:10:05" and exists (select * fromvehicles wheresales .vehicle_id =
vehicles .id ))
希望等待使用 eloquent 查询"获取销售量总和"的解决方案。
- 已编辑
您需要在对
1 2 3 4 | $totalVolume = Sale::where('status', 1) ->where('date_time', '<',"2017-05-10 10:10:05") ->join('vehicles', 'vehicles.id', '=', 'sales.vehicle_id') ->select(DB::raw('sum(vehicles.volume) as total_volume'); |