LoginSignup
0
1

More than 3 years have passed since last update.

[Laravel] groupByが実行される前にidが新しいグループ順のデータを取得したい時に「whereIn」が使えた

Posted at

WhereIn 備忘録

whereInの使い方は、以下のwhereInを参照してください。
https://readouble.com/laravel/6.x/ja/queries.html
SQLのWHERE ~ IN ~ と同じ使い方なので大丈夫だとは思いますが、
SQLだと


SELECT *
FROM sports
WHERE name 
IN('baseball','football','basketball');

のように記述できるところを

DB::table('sports')->whereIn('name', ['baseball', 'football', 'basketball']);

というように簡単に記述することができるのです。

本題ですが、
以下のようなテーブルがあり、question_idは別にquestionテーブルがあってリレーションしてる状態です。
question_idは1~3まであるとして、下のテーブルから
id = [4, 5, 6]のデータを取得したいのですが、
groupByを使用すると古い(idが若いもの id = [1,2,6])を取得してきてしまいます。

report テーブル

id question_id
1 2
2 1
3 1
4 1
5 2
6 3

そのため、以下のようなコードを実行するとうまくいきました。
reportのidカラム(whereIn第一引数)のなかで、
report question_idでグループ化されたレコードでreportのidが大きいもののリスト(whereIn第二引数)
のデータを取得する。


DB::table('report')
    ->whereIn('report.id', function($query) {
        $query->select(DB::raw('MAX(report.id)'))
        ->from('report')
        ->groupBy('report.question_id');
    );

もっと他に良い書き方あるはずなんだろうけどとりあえず解決。

0
1
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
0
1