1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelクエリビルダmemo②(サブクエリのJOIN)

Last updated at Posted at 2020-03-02

laravelのクエリビルダに関してのメモです。

やりたいこと

サブクエリをJOINしたい。

joinSub()

公式リファレンス
https://readouble.com/laravel/5.8/ja/queries.html?header=%25E3%2582%25B5%25E3%2583%2596%25E3%2582%25AF%25E3%2582%25A8%25E3%2583%25AA%25E3%2581%25AEJOIN

今回はサブクエリで追加するカラムにデータがない場合も取得をしたいためleftjoin()で外部結合します。
leftjoinSub()の引数には、サブクエリ、テーブルのエイリアス、クロージャを定義します。
クロージャ内には結びつけるカラムの条件式を定義します。

//サブクエリ
$rating_avgs = Review::selectRaw('movie_id, AVG(rating) as rating_avg')->groupBy('movie_id');

$movie = Movie::leftjoinSub($rating_avgs, 'rating_avg', function($join){
            $join->on('movies.id', '=', 'rating_avg.movie_id');})
           ->get();

サブクエリのrating_avgが同時に取得できています。

=> Illuminate\Database\Eloquent\Collection {#3155
     all: [
       App\Models\Movie {#3140
         id: 1,
         user_id: 1,
         title: "Title1",
         director: "Director1",
         actor: "Actor1",
         text: "これはテスト投稿1です。",
         deleted_at: null,
         created_at: "2020-03-01 05:04:58",
         updated_at: "2020-03-01 05:04:58",
         movie_id: 1,
         rating_avg: "3.0000",
       },
       App\Models\Movie {#3125
         id: 2,
         user_id: 2,
         title: "Title2",
         director: "Director2",
         actor: "Actor2",
         text: "これはテスト投稿2です。",
         deleted_at: null,
         created_at: "2020-03-01 05:04:58",
         updated_at: "2020-03-01 05:04:58",
         movie_id: 2,
         rating_avg: "4.0000",
       },
     ],
   }
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?