テーブル例
たとえば下記のようなデータベーステーブルがあるとします。
モデル名はLogとして、日毎にカウント(count)の合計を出したいとします。
| id | INT |
|---|---|
| count | INT |
| created_at | TIMESTANP |
月別の集計
2019年の月毎に集計したい場合、まずはwhereYearで2019年を検索します。
groupByでformat('m')にすると月別にまとまるので、最後にmapでsumします。
Log::whereYear('start_at', 2019)
->orderBy('created_at')
->get()
->groupBy(function ($row) {
return $row->created_at->format('m');
})
->map(function ($day) {
return $day->sum('count');
});
日別の集計
日別の場合whereMonthで集計したい月を追加します。
groupByの部分を日のdに変更するだけです。
2019年9月を日別に集計したい場合は次のようになります。
Log::whereYear('created_at', 2019)
->whereMonth('created_at', 9)
->orderBy('created_at')
->get()
->groupBy(function ($row) {
return $row->created_at->format('d');
})
->map(function ($day) {
return $day->sum('count');
});



