4
0

More than 1 year has passed since last update.

Laravelでwhere句のグループ化

Posted at

where句のグループ化

以前入っていた現場で

select * from users
where ((status = 1) and (confirm_email1 = ? or confirm_email2 = ? or confirm_email3 = ?))
or ((status = 2) and (approve_email1 = ? or approve_email2 = ? or approve_email3 = ?))

上記のようなSQL文をLaravelで再現する必要がありました。(実際のコードから修正してあります)
そして私が最初に書いたコードはこんな感じでした。

$users =  User::query()
    ->Where('status', 1)
    ->orWhere('confirm_email1', $email)
    ->orWhere('confirm_email2', $email)
    ->orWhere('confirm_email3', $email)
    ->orWhere('status', 2)
    ->orWhere('approve_email1', $email)
    ->orWhere('approve_email2', $email)
    ->orWhere('approve_email3', $email)

絶対こんなコードではデータを取得できないよなと思いつつもこんなコードしか書けなかったです。。。。

色々調べていく中でwhereメソッドにクロージャを渡してグループ化できることを知りました。
そして進化したコードがこちらです!

$users =  User::query()
    ->where(function($query) use ($email) {
        $query->where(function($query) use ($email) {
            $query->Where('status', 1);
        })->where(function($query) use ($email) {
            $query->orWhere('confirm_email1', $email)
                  ->orWhere('confirm_email2', $email)
                  ->orWhere('confirm_email3', $email);
        });
    })
    ->orwhere(function($query) use ($email) {
        $query->where(function($query) use ($email) {
            $query->Where('status', 2);
        })->where(function($query) use ($email) {
            $query->orWhere('approve_email1', $email)
                  ->orWhere('approve_email2', $email)
                  ->orWhere('approve_email3', $email);
        });
    })
    ->get();

このコードを書いてうまくデータを取得できたときは少し感動しました。

参考にしたサイトはこちらです
Laravel readouble, 論理グループ化

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