You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:24:07