2016-07-05 57 views
0

有一個多字段搜索表單在我的Laravel 5.2的應用程序laravel多場搜索表單

price 
rooms 
type 
rent 

我有一些事情我錯了沒有結果正確,我認爲,因爲IM使用orWhere()。我想要和輸入字段之間。我想爲此提供任何解決方案

public function search() 
    { 

     $un_price = \Request::get('un_price'); 
     $un_rooms = \Request::get('un_rooms'); 
     $un_type = \Request::get('un_type'); 
     $un_rent = \Request::get('un_rent'); 
     $units = DB::table('units')->whereIn('un_status', [1]) 
      ->where('un_price','like','%'.$un_price.'%') 
      ->orWhere("un_rooms", "LIKE", "%$un_rooms%") 
      ->orWhere("un_type", "LIKE", "%$un_type%") 
      ->orWhere("un_rent", "LIKE", "%$un_rent%") 
      ->paginate(20); 
     return view('home.units.show', compact('units')); 
} 
+0

只是用where而不是orWhere呢? –

+0

當我使用哪裏只有我什麼都沒有得到 – fido

+0

concat變量與%標記在orWhere字段喜歡在你的where字段,否則你正在尋找「un_rooms like'%$ un_rooms%'」... –

回答

2

使用查詢字符串過濾。難道是這樣的:

public function search(Request $request) 
{ 
    $unit = (new Unit)->newQuery(); //where Unit is the model 
    if($request->has('un_price'){ 
     $unit->where('un_price',$request->un_price) 
    } 
    if($request->has('un_rooms'){ 
     $unit->where('un_rooms',$request->un_rooms) 
    } 
    //go on until the end 
    $units = $unit->get(); 
    return view('home.units.show', compact('units')); 
} 

這種方式,您得到您根據您收到的輸入需要的所有結果。

+0

非常感謝它的工作良好 – fido

+0

在這種情況下,我如何搜索un_price和添加兩個輸入字段un_price_from和un_price_to – fido

+1

elseif($ request-> has('un_price_from','un_price_to')){unit_> whereBetween('un_price',[$ request - > un_price_from,$ request-> un_price_to]); } – fido