LoginSignup
0
0

More than 3 years have passed since last update.

LaravelのEloquentで、グループごとに日付が最新の行を取得したいときのテク

Last updated at Posted at 2020-11-21

たとえば、サロンの予約テーブルがあるとしたら、
ユーザーごとに日付が最新の予約だけを取得したいときに使えるテク。

前提

// NGな例
$reservations = Reservation
    ::groupBy('user_id')
    ->selectRaw('user_id, max(visit_salon_time)')
    ->get();

みたいな感じで良さそうだが、これだとuser_idvisit_salon_timeしか取得できない。
集計が効かないカラムの取得には工夫が必要。

具体的な方法

別の書き方は複数存在するが、以下のコードはサブクエリが不要でシンプル。

$reservations = Reservation
    ::leftJoin(
        'reservations as reservations2',
        function ($join) {
            $join->on('reservations.user_id', 'reservations2.user_id')
                ->whereColumn('reservations.visit_salon_time', '<', 'reservations2.visit_salon_time');
        }
    )
    ->whereNull('reservations2.user_id')
    ->get();

ざっくり解説

同じテーブルを条件付きでleftJoinして、日付が最新の行はJoinされないようにする。
JoinされたテーブルのいずれかのカラムがNullであれば最新。

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