LoginSignup
2
3

More than 3 years have passed since last update.

Laravelクエリビルダmemo➀(集計関数)

Posted at

laravelのクエリビルダの集計に関するメモです。

やりたいこと

グループ化してから平均をとりたい。

問題点

はじめはクエリビルダの集計関数のavg()で試みたのですがgraupBy()と併用できないのです。

直接クエリを書く

そこで集計のところをサブクエリとして、selectRaw()で直接クエリを書いてから、graupBy()でグループ化します。

公式リファレンス
https://readouble.com/laravel/5.8/ja/queries.html?header=selectRaw


$rating_avgs = Review::selectRaw('movie_id, AVG(rating) as rating_avg')->groupBy('movie_id')->get();

無事取得できました。

=> Illuminate\Database\Eloquent\Collection {#3141
     all: [
       App\Models\Review {#3132
         movie_id: 1,
         rating_avg: "3.0000",
       },
       App\Models\Review {#3135
         movie_id: 2,
         rating_avg: "4.0000",
       },
     ],
   }

movie_idも取得するのは、サブクエリをJOINするためです。

avg()だけでなくcount()max()なども同じような感じになると思います。
こういうところでlaravelの集計関数の限界を感じます。

2
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
2
3