选择价格总和等于laravel或1000的所有行

时间:2018-08-29 22:33:03

标签: php mysql laravel

我要选择价格列总和为1000或以下的所有行。如何使用Laravel实现它?请提出建议。我是laravel的新手。

我的桌子只有4列

  1. id
  2. userid
  3. order_id
  4. price

我需要使用traditional DB::table('orders')->select()... query (not using model)选择所有行,其中价格列的总值为1000。

2 个答案:

答案 0 :(得分:1)

我知道OP要求使用RAW SQL语句,但是由于使用 Laravel ,获得这些订单的最佳方法是利用这样的 Laravels Eloquent 引擎:

$orders = Orders::select(userid, order_id, DB::raw('SUM(price) as price_total'))
->groupBy('order_id')
->havingRaw('SUM(price) <= ?',[1000])
->get();

顺便说一句,如果 userid 坚持使用像 user_id 这样的laravel约定会更好,但这是另一种情况。

如果您打算这样做,那么应该可以轻松地将此请求分组为userid,而不是order_id

答案 1 :(得分:0)

巴特回答的信用

$orders = DB::table('orders')
       ->where('price','<=',1000)
       ->select(
         DB::raw(
            'col1,
             col2,
             col3,
             sum AS "price_total"')
      )
      ->get();
相关问题