如何在Laravel中编写带left join、sum计算的SQL查询?
Laravel 购物车总金额统计查询实现方案
你需要的SQL可以通过以下两种Laravel原生支持的方式实现,自动处理参数绑定避免SQL注入风险:
- 使用DB查询构造器实现(无需创建对应模型即可使用)
use Illuminate\Support\Facades\DB; $user_id = Auth::id(); $total = DB::table('carts') ->leftJoin('food', 'carts.food_id', '=', 'food.id') ->where('carts.user_id', $user_id) ->where('carts.status', '0') ->selectRaw('SUM(food.price * carts.quantity) as total') ->value('total'); // 无匹配数据时$total为null,可通过 `$total = $total ?? 0` 转为默认0值
- 使用Eloquent模型实现(如果已创建Cart模型的更简洁写法)
$total = \App\Models\Cart::query() ->leftJoin('food', 'carts.food_id', '=', 'food.id') ->where('user_id', Auth::id()) ->where('status', '0') ->selectRaw('SUM(food.price * carts.quantity) as total') ->value('total');
说明:
selectRaw方法可以直接写入原生SQL计算逻辑,value方法直接取出统计字段的结果,无需遍历查询结果集,性能开销更低。
内容的提问来源于stack exchange,提问作者Ilyosjon Saydaliyev
相关产品推荐
相关产品推荐

