【问题标题】:How to write this sql,left join,sum query in Laravel? How to use sum with left join in Laravel?如何在 Laravel 中编写这个 sql、left join、sum 查询?如何在 Laravel 中使用 sum 和左连接?
【发布时间】:2021-11-07 13:33:01
【问题描述】:

我想用 laravel 写这个查询,

我的表结构是

有一个用户ID $user_id = Auth::id();

购物车-> ID|USER_ID|FOOD_ID|QUANTITY|STATUS

食物-> ID|名称|价格

SELECT sum(food.price*carts.quantity) as total 
from carts  
left join food on carts.food_id=food.id 
where user_id=$user_id and status='0'

【问题讨论】:

    标签: php mysql laravel sum structure


    【解决方案1】:

    你也可以这样试试:

    $res = DB::table('carts')
             ->select(DB::Raw('SUM(food.price*carts.quantity) AS total'))
             ->leftJoin('food', 'carts.food_id', 'foods.id')
             ->where('carts.user_id', $user_id)
             ->where('carts.status', 0)
             ->first();
    

    【讨论】:

      【解决方案2】:

      使用查询生成器:

      $amount = \DB::table('carts')
              ->where('carts.user_id', $user)
              ->where('carts.status', '!=', 0)
              ->leftJoin('foods', 'carts.food_id', 'foods.id')
              ->sum(\DB::raw('carts.quantity * foods.price'));
      

      【讨论】:

        猜你喜欢
        • 2015-10-19
        • 2019-06-17
        • 2016-03-24
        • 1970-01-01
        • 2019-12-20
        • 1970-01-01
        • 2015-02-22
        • 2018-08-18
        • 1970-01-01
        相关资源
        最近更新 更多