如何在Laravel中编写这个sql、left join、sum查询?如何在 Laravel 中使用 sum 和 left join?
How to write this sql,left join,sum query in Laravel? How to use sum with left join in Laravel?
我想在laravel,
中写这个查询
我的table结构是
有用户id
$user_id = Auth::id();
手推车->
ID|USER_ID|FOOD_ID|数量|状态
食物->
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'
使用查询生成器:
$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'));
你也可以这样试试:
$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();
我想在laravel,
中写这个查询我的table结构是
有用户id $user_id = Auth::id();
手推车-> ID|USER_ID|FOOD_ID|数量|状态
食物-> 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'
使用查询生成器:
$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'));
你也可以这样试试:
$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();