Search code examples
phpmysqllaravelsumstructure

How to write this sql,left join,sum query in Laravel? How to use sum with left join in Laravel?


I want to write this query in laravel,

My table structures are

There is a user id $user_id = Auth::id();

CARTS-> ID|USER_ID|FOOD_ID|QUANTITY|STATUS

FOOD-> ID|NAME|PRICE

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'

Solution

  • You can also try this way:

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