将SQL查询转换为Laravel构建器时遇到困难

时间:2017-02-28 11:39:15

标签: php sql laravel

我正在尝试使用查询构建器将以下查询转换为laravels,但是对group by子句和sum聚合函数存在一些问题

SELECT code, SUM(quantity) as quantity, SUM(sale_price) as price
FROM `orders` o
GROUP By code

我试过这个,这是我经过这么多绝望的尝试之后所拥有的。

$args['orders'] = DB::table('orders')
->havingRaw('sum(sale_price)')
->havingRaw('code')
->where([ 'shop_id' => $shop_id ])
->groupBy('code')
->get();

1 个答案:

答案 0 :(得分:1)

尝试

$args['orders'] = DB::table('orders')
->where('shop_id', '=', $shop_id)
->select('code', DB::raw('sum(quantity) as quantity, sum(sale_price) as price'))
->groupBy('code')
->get();

排序
$args['orders'] = DB::table('orders')
->where('shop_id', '=', $shop_id)
->select('code', DB::raw('sum(quantity) as quantity, sum(sale_price) as price'))
->groupBy('code')
->orderBy('quantity')
->get();

或尝试

->orderByRaw('sum(quantity)')