Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading