世人谓我恋长安,其实只恋长安某。
今天在做按照商品的SPU批量采购的时候, 遇到了一个问题, 就是安装SPU`groupBy`后计算的`sum`值仅仅只是每个SPU下的产品数量之和, 这可以满足在每个列表中的正常显示,但是现在需要在页面的顶部显示一个全部的SPU下的产品数量, 因为数据是分页的, 就很难计算了.起初我的代码是这样的:
1 2 3 4
| $query = WaitingForPurchase::query() ->selectRaw('id, site_id, ps_type_id, ps_shop_id, ps_product_id, order_product_id, shop_product_id, sum(qty) as qty') ->where(['ps_type_id' => $type_id, 'ps_shop_id' => $shop_id]) ->groupBy('shop_product_id')
|
在GOOGLE了一番以后, 才知道mysql
竟然还有这样的用法
1 2 3 4
| $query = WaitingForPurchase::query() ->selectRaw('id, site_id, ps_type_id, ps_shop_id, ps_product_id, order_product_id, shop_product_id, sum(qty) as qty') ->where(['ps_type_id' => $type_id, 'ps_shop_id' => $shop_id]) ->groupBy(DB::raw('shop_product_id WITH ROLLUP'));
|
这样得到的结果就是在我们的查询结果中会多出一条数据,用来显示额外的统计信息.
在使用Laravel框架的情况下, 我们还可以这样统计:
1 2 3 4 5 6 7 8 9 10 11 12
| $query = WaitingForPurchase::query() ->selectRaw('id, site_id, ps_type_id, ps_shop_id, ps_product_id, order_product_id, shop_product_id, sum(qty) as qty') ->where(['ps_type_id' => $type_id, 'ps_shop_id' => $shop_id]);
WaitingForPurchase::setFilters($query, $conditions);
$sum = $query->sum('qty');
$query->groupBy('shop_product_id') ->orderByDesc('qty');
$items = $query->paginate(20);
|