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

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

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

Sale 模型上的关系是:

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

表 sales 具有以下字段:
id 、 vehicle_id 、 date_time 、 status 等

表 vehicles 具有以下字段:
id 、 reg_number 、 volume 、 status 等

我想要的是搜索条件内 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 查询"获取销售量总和"的解决方案。

  • 已编辑



相关讨论

  • 我认为您应该首先写出如果您直接使用 Workbench 将运行的原始 MySQL 查询。然后,基于此,构建 Laravel 查询。如果你不能编写 MySQL 查询,那么你可能还没有准备好攻击 Laravel 方面。


您需要在对 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' ) ;



相关讨论

  • 谢谢马丁.. $totalQuantity = $totalQuantityQuery->join('vehicles', 'vehicles.id', '=', 'sales.vehicle_id')->select(\\DB::raw('sum(vehicles.volume) as total_volume'))->get() 在数组中给出了一个对象.. 使用.. $totalQuantity[0]->total_volume 提取结果


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

本文由 华域联盟 原创撰写:华域联盟 » 关于 php:如何在 Laravel 中对相关表的字段进行聚合查询?

转载请保留出处和原文链接:https://www.cnhackhy.com/158100.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部