LoginSignup
5
2

More than 3 years have passed since last update.

【Laravel】クエリビルダでWhere句にA OR (B AND C)を書く

Posted at

使用する機会があり、メモ程度にまとめてみます。

環境

PHP : 5.6.30
MySQL : 10.1.21
Laravel : 5.1.46

テーブル

以下サンプルテーブルです。

id name created_date updated_date
1 Suzuki Taro 2019-01-01 12:00:00 2019-01-01 12:00:00
2 Tanka Hanako 2019-01-25 10:00:00 2019-01-29 12:00:00
3 Takahashi Jiro 2019-02-01 16:00:00 2019-02-01 16:00:00

元のSQL

SELECT name FROM users
WHERE (created_date BETWEEN '2019-01-01 00:00:00' AND '2019-01-01 23:59:59'
OR (updated_date < '2019-02-01' AND id >= 1));

クエリビルダでの書き方

$test = Users::query()
   ->select('name')
   ->where(function ($query) {
                // created_dateが2019-01-01中
                $query->whereBetween('created_date', ['2019-01-01 00:00:00', '2019-01-01 23:59:59'])
                    // またはupdated_dateが2019-02-01より前、かつidが1以上
                    ->orWhere(function ($query) {
                        $query->where('updated_date', '<', '2019-02-01')
                            ->where('id', '>=', 1);
                    });
            })
5
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
5
2