
SQL
SELECT
DATE_FORMAT(request_date, "%Y-%m") AS request_month,
COUNT(*) AS request_count,
SUM(requests) AS request_sum
FROM member_requests
WHERE member_id = 100 // 任意
AND DATE_FORMAT(request_date, "%Y") = 2021 // 任意
GROUP BY request_month
クエリビルダに変換
/**
* 会員のリクエスト集計
*
* @param int $member_id
* @param string $year
*/
public function getSummary(int $member_id, string $year)
{
$query = $this->resource->query();
return $query->select([
\DB::raw('DATE_FORMAT(request_date, "%Y-%m") AS request_month'),
\DB::raw("COUNT(*) AS request_count"),
\DB::raw("SUM(requests) AS request_sum"),
])
->where('member_id', $member_id)
->where('request_date', 'LIKE', $year . '%')
->groupBy('request_month') // SELECTでフォーマットしたカラムで検索できる
->get();
}
関連記事 - More from my site -