LoginSignup
5
3

More than 1 year has passed since last update.

【Laravelクエリビルダ】idをgroupByし、SUMで集計する方法

Last updated at Posted at 2021-07-03

この記事ではLaravelのクエリビルダ初級者向けにgroupByとSUMで集計結果を解説していきます。

バージョンは6系です。

ブログで以下のような記事も書いています。

取得するデータについて

今回の取得するデータは以下の通りです。

studentsテーブル
スクリーンショット 2021-07-03 17.35.13.png

studentsテーブルのpost_idでグループ化し、amountの合算値を取得したいって場合。

同じpost_idをまとめて、amountを合算します。
イメージとしては、以下です。

post_id amount
1 1000
2 2000
3 3000
1 5000

post_id amount
1 6000
2 2000
3 3000

SQLで書くと以下のようになります。

SELECT
post_id,
SUM(amount) AS total_amount
FROM students
GROUP BY post_id

これをクエリビルダにすると以下になります。

$result = DB::table('students')
     ->select('post_id')
     ->selectRaw('SUM(amount) AS total_amount')
     ->groupBy('post_id')
     ->get();

コードを解説

DB::table('students')は、テーブルを指定。

selectRaw

select('post_id')SELECT文。post_idをセレクトする。

selectRaw('SUM(amount) AS total_amount')について。
selectRawとは、select(DB::raw(...))の省略形です。
DB::raw()とは、SQLを直接使用できるものです。ただ、生のSQLを書くことはセキュリティの面で心配なので、積極的には利用しない方がいいんですよね。
だけど、SUM関数などをクエリビルダで書くときは、selectRawを使う方法しかないですよ。
※もしあればコメントでお知らせください。
AS total_amountでtotal_amountというカラム名に変更してます。

groupBy

groupBy('post_id')でpost_idをグループ化してます。
これにより、post_idが1,2,3,1→1,2,3になります。

最後にget()でデータを取得してます。

中で行っていることとしては、
post_id amount
1 1000
2 2000
3 3000
1 5000

これを
1 6000
2 2000
3 3000

にまとめたって感じですね。

ビューで以下のように書けば、データを取得できます。

<table>
    <thead>
      <tr>
        <th>投稿ID</th>
        <th>合計金額</th>
      </tr>
    </thead>
    <tbody>
    @foreach ($result as $val)
      <tr>
        <td>{{ $val->post_id }}</td>
        <td>{{ $val->total_amount }}</td>
      </tr>
    @endforeach
    </tbody>
</table>

スクリーンショット 2021-07-03 17.56.54.png

今回はここまでです。
参考になりましたらLGTMや記事のストックをお願いいたします。

ブログで以下のような記事も書いているのでぜひ一読してみてくださいね!

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3