在 laravel 查询中使用聚合方法(此处为 SUM)进行复杂查询

Using aggregate methods( SUM as of here) in laravel query for complex queries

我必须 运行 查询以找出每个数量的订单总数

  SELECT userorders.`delivered` as delivered_status, items.`name` as itemname, 
sizes.`size` as sizename,SUM(userorders.`order_qty`) as order_quantity, 
sizes.`qty` as stockremaining FROM userorders inner join sizes on 
userorders.`size`=sizes.`id` inner join items on  sizes.`item_id`=items.`id`
 WHERE 1 group by userorders.`delivered`, userorders.`size`;

粗略地说,它的 laravel 相当于

 $userorders = DB::table('userorders')
            ->join('sizes', 'userorders.size', '=', 'sizes.id')
            ->join('items', 'sizes.item_id', '=', 'items.id')
            ->join('categories', 'items.category_id', '=', 'categories.id')
            ->select('SUM(userorders.order_qty) as order_quantity','userorders.delivered as delivered_status', 'items.name as itemname','categories.name as categoryname', 'sizes.size as sizename','sizes.qty as stockremaining')
            ->groupBy('userorders.delivered', 'userorders.size')
            ->get();

但是,好像laravel不支持聚合参数。 我发现为了获得总数量,我们可以将其用作

$userorders = DB::table('userorders')
                ->join('sizes', 'userorders.size', '=', 'sizes.id')
                ->join('items', 'sizes.item_id', '=', 'items.id')
                ->join('categories', 'items.category_id', '=', 'categories.id')
                ->SUM('userorders.order_qty');

但在我的情况下,获取总和以及其他参数似乎不起作用。 有人可以建议我如何让它工作吗?

要将聚合与 eloquent 或查询构建器一起使用,您需要使用 raw 方法。大致是这样的:

->selectRaw('SUM(userorders.order_qty) as order_quantity','userorders.delivered as delivered_status', 'items.name as itemname','categories.name as categoryname', 'sizes.size as sizename','sizes.qty as stockremaining')

查看文档:https://laravel.com/docs/5.5/queries#raw-expressions

使用DB::raw:

$userorders = DB::table('userorders')
                ->select('userorders.delivered', 'userorders.size',
                          DB::raw('SUM(userorders.order_qty) as total_qty'))
                ->join('sizes', 'userorders.size', '=', 'sizes.id')
                ->join('items', 'sizes.item_id', '=', 'items.id')
                ->join('categories', 'items.category_id', '=', 'categories.id')
                ->groupBy('userorders.delivered', 'userorders.size');

注意我只select三件事,出现在GROUP BY子句中的两列和订单数量的总和。选择任何其他非聚合列在技术上都是无效查询(尽管 MySQL 可能会容忍它)。