doudun3910 2017-09-14 05:28
浏览 203
已采纳

如何在Laravel中相关表的字段上聚合查询?

I have a One To Many (Inverse) relation on my laravel 5.4 application. There are two models Sale and Vehicle which are related and associated with the scene.

The relation on the Sale model is :

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

Table sales has following fields : id, vehicle_id, date_time, status etc.

Table vehicles has following fields : id, reg_number, volume, status etc.

What I want is, sum of the field 'vehicles.volume' of Sale records within the search conditions.

I have tried some methods like the following one:

$query = Sale::where('status', 1);
$query = $query->where('date_time', '<', "2017-05-10 10:10:05");
$totalVolume  = $query->whereHas('vehicle')->sum('vehicles.volume');

and it resulted in the following error:

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

hopefully waiting for a solution to 'get the sum of the volume of the sales' using eloquent query.

  • Edited
  • 写回答

2条回答 默认 最新

  • dpbl91234 2017-09-14 13:11
    关注

    You need to use a join before summing the vehicles.volume column

    $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条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?