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

Laravel中如何复用条件对关联模型多列分别求和?

Laravel关联模型多列求和优化(避免重复where条件)

你当前的查询重复调用withSum且每次都重复写whereMonth('date', $month),既冗余又影响性能。可以利用Laravel withSum的特性,实现一次过滤条件下的多列求和:

正确实现代码

Section::withWhereHas('studentsInCurrentSession', function ($query) use ($month) {
    $query->withSum(
        ['attendances' => fn ($q) => $q->whereMonth('date', $month)],
        ['present', 'absent', 'leave']
    );
})->first();

说明

  • 第一个参数传入带约束的关联闭包:这里统一添加whereMonth过滤条件,所有求和列都会复用这个约束,不用重复写多次
  • 第二个参数传入需要求和的字段数组:一次性指定present、absent、leave三列,Laravel会自动生成对应的求和属性
  • 求和结果可以通过以下属性访问:每个Student实例会生成attendances_sum_present、attendances_sum_absent、attendances_sum_leave三个属性,直接调用即可获取对应总和

可选:自定义求和属性名

如果想要更直观的属性名,可以用键值对的方式指定:

Section::withWhereHas('studentsInCurrentSession', function ($query) use ($month) {
    $query->withSum(
        ['attendances' => fn ($q) => $q->whereMonth('date', $month)],
        [
            'total_present' => 'present',
            'total_absent' => 'absent',
            'total_leave' => 'leave'
        ]
    );
})->first();

此时可以通过$student->total_present、$student->total_absent、$student->total_leave访问求和结果。

内容的提问来源于stack exchange,提问作者Faizan Ahanger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 01:04:58