Laravel Group By 和其他列的总和值

mad*_*nan 2 php laravel

我的数据库中有一个表,如下所示:

id | date       | amount
========================
1  | 2015-01-26 | 1000
2  | 2015-02-26 | 100
3  | 2014-06-26 | 10
Run Code Online (Sandbox Code Playgroud)

我想按年份对记录进行分组,然后找到每组金额的总和。

我可以使用以下查询找到组:

Fee::orderBy('date', 'DESC')
  ->get()
  ->groupBy(function($date) {
    return Carbon::parse($date->date)->format('Y'); // grouping by years
})
Run Code Online (Sandbox Code Playgroud)

但我无法获得每组金额的总和。

haa*_*kym 11

恐怕我现在无法用 eloquent 弄清楚,但这应该适用于查询构建器。它对我来说工作正常:

DB::table('fees')
    ->select(DB::raw('YEAR(date) as year'), DB::raw('sum(amount) as total'))
    ->groupBy(DB::raw('YEAR(date)') )
    ->get();
Run Code Online (Sandbox Code Playgroud)

使用您在问题中输入的同一日期:

id       date                       amount
 1       2015-01-26                  1000
 2       2015-02-26                  100
 3       2014-06-26                  10
Run Code Online (Sandbox Code Playgroud)

它给出了以下内容:

array:2 [?
  0 => {#150 ?
    +"year": 2014
    +"total": "10"
  }
  1 => {#151 ?
    +"year": 2015
    +"total": "1100"
  }
]
Run Code Online (Sandbox Code Playgroud)