[Laravel] 使用orwhere的坑:SQL缺少了括號


如果直接使用
$query = DB::table('users')
           ->where('name' , 'like' , '%'.$search.'%')
           ->orWhere('email' , 'like' , '%'.$search.'%')
           ->where('status', 0)
           ->get();

得到的 SQL 為
SELECT * 
FROM users 
WHERE name like '%關鍵字%' or email like '%關鍵字%' and status = 0

如果你希望的結果是
SELECT * 
FROM users 
WHERE (name like '%關鍵字%' or email like '%關鍵字%') and status = 0

laravel 語法要改寫成
$query = DB::table('users')
           ->where(function($query) use($search) {
              $query->where('name' , 'like' , '%'.$search.'%')
                    ->orWhere('email' , 'like' , '%'.$search.'%'); 
             })
           ->where('status', 0)
           ->get();

Source

Laravel使用orwhere括號位置
Laravel 5.0 Query Builder - Where with multiple parameters

Image Source

Laravel orWhere Condition with Eloquent Query Example

沒有留言:

技術提供:Blogger.