117
84

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

Laravel5で「.. or ...) and (..」みたいな複雑な条件を書く

Last updated at Posted at 2015-11-30

SELECT * FROM tbl_data WHERE (column_a = 'hoge' or column_a= 'piyo') 
                         AND (column_b= 'foo' or column_b= 'bar');

こういうSQLを書きたい場合、->whereや->orWhereでどうすれば良いか。


$query =  TblDatum::where(function($query){
                        $query->orWhere('column_a', '=', 'hoge')
                              ->orWhere('column_a', '=', 'piyo');
                    })->where(function($query){
                        $query->orWhere('column_b', '=', 'foo')
                              ->orWhere('column_b', '=', 'bar');
                    });

こうなりました。
'='は省略してもいいです。

変数使うときはuseを使います。

$query =  TblDatum::where(function($query) use ($hoge, $piyo) {
                        $query->orWhere('column_a', '=', $hoge)
                              ->orWhere('column_a', '=', $piyo);
                    })->where(function($query) use ($foo, $bar) {
                        $query->orWhere('column_b', '=', $foo)
                              ->orWhere('column_b', '=', $bar);
                    });
117
84
1

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
117
84

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?