7
2

More than 3 years have passed since last update.

EloquentのJOINで結合テーブルに論理削除を効かせる

Posted at

EloquentでModelに論理削除(SoftDeletes)を設定しておくと、デフォルトでdeleted_at is nullをWHERE条件に入れてSQLを発行してくれます。

しかし、テーブル結合(JOIN)をした場合、結合したテーブルに対して論理削除の抽出条件が効きません。

$users = User::join('deptments', 'users.deptment_id', '=', 'deptments.id')->get();
select
  * 
from
  `users` 
  inner join `deptments` 
    on `users`.`deptment_id` = `deptments`.`id` 
where
  `users`.`deleted_at` is null

それならとwhereを設定してみるも、これだとLEFT JOINの場合に結合しなかったusersテーブルのレコードが抽出されなくなってしまいます。

$users = User::join('deptments', 'users.deptment_id', '=', 'deptments.id')
             ->where('deptments.deleted_at', null)->get();
select
  * 
from
  `users` 
  inner join `deptments` 
    on `users`.`deptment_id` = `deptments`.`id` 
where
  `deptments`.`deleted_at` is null 
  and `users`.`deleted_at` is null

第二引数にクロージャを渡すとJOIN句の中で複数の抽出条件を使えるようになります。

$users = User::join('deptments', function ($join) {
            $join->on('users.deptment_id', '=', 'deptments.id')
                 ->where('deptments.deleted_at', null);
         })->get();
select
  * 
from
  `users` 
  inner join `deptments` 
    on `users`.`deptment_id` = `deptments`.`id` 
    and `deptments`.`deleted_at` is null 
where
  `users`.`deleted_at` is null

意図したSQLを発行することができました。

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