0
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 3 years have passed since last update.

Laravel クエリビルダーを使ったandやorを複数書きたい

Last updated at Posted at 2021-04-06

SQLで

SELECT * FROM xxx
where id = 1
AND (
  type = 1 
  OR (type = 2 AND version = 1)
  OR (type = 2 AND version = 2)
);

のようなSQLを書きたい時があったがカッコの部分でうまくいかなくて困ったことがあったので忘れないように残しておく

xxx::query()
  ->where('id', 1)
  ->where(function ($query) {
    $query->where('type', 1);
    $query->orWhere(function ($query_inner) {
      $query_inner->orWhere('type', 2);
      $query_inner->where('version', 1);
    });
    $query->orWhere(function ($query_inner2) {
      $query_inner2->orWhere('type', 2);
      $query_inner2->where('version', 2);
    }); 
 })->get();

このように書くことで想定のSQLになった。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?