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

如何在Laravel中按会员与年份分组聚合金额?

Laravel Eloquent 分组汇总金额问题

现有members表数据

memberYearAmount
Vinoth20151000
Vinoth20161000
Vinoth2016300
Prabu20151000
Prabu20161000
Ravanan2016100
Vinoth20163000
Vinoth20163000

预期查询结果

需要按会员+年份分组,汇总对应金额,得到如下结果:

memberYearAmount
Vinoth20151000
Vinoth20167300
Prabu20151000
Prabu20161000
Ravanan2016100

已尝试的代码

Member::select('SUM(amount) as amount', 'year', 'member')->groupby('year')->get();

解决方法

你的代码问题在于仅按year分组,但我们需要同时按member和year两个字段分组,才能实现会员+年份的组合汇总。另外,Laravel中直接在select里写聚合函数需要用DB::raw()或者selectRaw()来解析SQL表达式。

正确代码示例:

方法一:使用selectRaw

Member::selectRaw('member, year, SUM(amount) as total_amount')
    ->groupBy('member', 'year')
    ->get();

方法二:使用DB::raw

use Illuminate\Support\Facades\DB;

Member::select(
        'member',
        'year',
        DB::raw('SUM(amount) as total_amount')
    )
    ->groupBy('member', 'year')
    ->get();

说明:

  1. 分组字段必须包含所有非聚合的查询字段(这里就是member和year),否则会违反SQL的分组规则。
  2. 可以将汇总后的字段名改为total_amount(也可保持amount),更清晰区分原始字段和汇总结果。
  3. 如果Laravel开启了严格模式(默认开启),确保groupBy包含所有非聚合字段,避免SQL报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:05:27