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 :

Using Query Builder:

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

Leave a Reply