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

时间:2018-01-19 05:38:24

标签: mysql sql laravel laravel-eloquent

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

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

但似乎在我的情况下也不能用于获得总和以及其他参数。 有人可以建议我如何让它发挥作用吗?

2 个答案:

答案 0 :(得分:1)

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

请注意,我只选择了三个内容,GROUP BY子句中出现的两列以及订单数量的总和。选择任何其他非聚合列在技术上是一个无效的查询(虽然MySQL可能会容忍它)。

答案 1 :(得分:0)

要使用具有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