关于 php:如何在 Laravel 中对相关表的字段进行聚合查询?

How to aggregate query on related table's field in Laravel?

我的 laravel 5.4 应用程序有一个一对多(反向)关系。有两个模型 SaleVehicle 与场景相关和关联。

Sale 模型上的关系是:

1
2
3
4
public function vehicle()
    {
        return $this->belongsTo('App\\Models\\Vehicle','vehicle_id');
    }

sales 具有以下字段:
idvehicle_iddate_timestatus

vehicles 具有以下字段:
idreg_numbervolumestatus

我想要的是搜索条件内Sale条记录的"vehicles.volume"字段的总和。

我尝试了一些方法,如下所示:

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 from sales where status = 1
and date_time <"2017-05-10 10:10:05" and exists (select * from vehicles where sales.vehicle_id =
vehicles.id))

希望等待使用 eloquent 查询"获取销售量总和"的解决方案。

  • 已编辑


您需要在对 vehicles.volume 列求和之前使用连接

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');


1
select sum(volume) as aggregate from vehicles INNER JOIN sales ON vehicles.id=sales.vehicle_id