在laravel查询中使用聚合方法(sum-as-of-here)进行复杂查询

8ehkhllq  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(420)

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

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`;

粗略地说,它的拉威尔当量是

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

但在我的例子中,它似乎不适用于求和以及其他参数。有人能告诉我怎么做吗??

uqjltbpv

uqjltbpv1#

使用 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可能会容忍它)。

pxiryf3j

pxiryf3j2#

要将聚合与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-表达式

相关问题