2017-04-13 35 views
6

我需要幫助查詢在laravel如何使用多個OR,並在Laravel條件查詢

我的自定義查詢:(返回正確的結果)

Select * FROM events WHERE status = 0 AND (type="public" or type = "private") 

如何編寫Laravel此查詢。

Event::where('status' , 0)->where("type" , "private")->orWhere('type' , "public")->get(); 

但是它返回所有的公共事件狀態不是0爲好。

我使用Laravel 5.4

回答

1

使用此

$event = Event::where('status' , 0); 

$event = $event->where("type" , "private")->orWhere('type' , "public")->get(); 

或本

Event::where('status' , 0) 
    ->where(function($result) { 
     $result->where("type" , "private") 
      ->orWhere('type' , "public"); 
    }) 
    ->get(); 
+0

感謝這一項工作以及。 –

0

你的情況,你可以重寫查詢...

select * FROM `events` WHERE `status` = 0 AND `type` IN ("public", "private"); 

而且具有雄辯:

$events = Event::where('status', 0) 
    ->whereIn('type', ['public', 'private']) 
    ->get(); 

當你想有一個分組或/和,使用閉包:

$events = Event::where('status', 0) 
    ->where(function($query) { 
     $query->where('type', 'public') 
      ->orWhere('type', 'private'); 
    })->get(); 
0

試試這個。這個對我有用。

$rand_word=Session::get('rand_word'); 
$questions =DB::table('questions') 
    ->where('word_id',$rand_word) 
    ->where('lesson_id',$lesson_id) 
    ->whereIn('type', ['sel_voice', 'listening']) 
    ->get();