2016-10-29 242 views
4

我正在做一個搜索過濾器,我有3個輸入「市」,「類別」,「關鍵字」,我試着插入值數組如果輸入不是空的。像這樣:Laravel 5.2 - 過濾器陣列

public function search(Request $request) 
    { 


     $filter = array(["'visible', '=' , 1"],["'expire_date', '>', $current"]); 

     if(!empty($termn)){ 
       $filter[] =["'title', 'LIKE' , '%'.$termn.'%'"]; 
     } 
     if(!empty($request->input('category'))){ 
       $filter[] = ["'category_id', '=', $input_category"]; 
     } 
     if(!empty($request->input('municipality_id'))) { 
       $filter[] = ["'municipality_id', '=', $input_municipality"]; 
     } 

     dd($filter); 

     $posts = Post::where($filter)->get(); 
} 

但它不是過濾好,DD($濾波器)返回這樣的: enter image description here

也許陣列的結構是不好的,我也嘗試這樣的: laravel 5.2 search query 但它不工作。 無DD($過濾器)我有此錯誤:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '. is null and `'municipality_id', '=', 1` is null)' at line 1 (SQL: select * from `posts` where (`'visible', '=' , 1` is null and `'expire_date', '>', 2016-10-29 13:29:30` is null and `'category_id', '=', Scegli una categoria`. . . is null and 'municipality_id', '=', 1 is null))

謝謝您的幫助!

+1

考慮寫更好的問題。那裏有這麼多。就像「輸入」一樣,檢查是否有空。如果你只是說'$ filter = [..]; $ posts = Post :: where($ filter) - > get();'給出瞭如此之多的錯誤。我究竟做錯了什麼?您將以這種方式獲得更多答案。 –

回答

1

您正在使用的where子句錯誤。請參閱以下文檔:

選項,其中在模型條款應該作爲參數在鏈接方法被髮送(NOT數組值)像這樣:

public function search(Request $request) 
    { 
     $current = Carbon::now(); 
     $current = new Carbon(); 
     $termn = $request->input('keyword'); 
     $input_category = $request->input('category'); 
     $input_municipality = $request->input('municipality_id'); 


     $posts = Post::where('visible', 1)->where('expire_date', '>', $current); 

     if(!empty($termn)){ 
       $posts->where('title', 'LIKE' , '%'.$termn.'%'); 
     } 
     if(!empty($request->input('category'))){ 
       $posts->where('category_id', '=', $input_category); 
     } 
     if(!empty($request->input('municipality_id'))) { 
       $posts->where('municipality_id', '=', $input_municipality); 
     } 

     $post_results = $posts->get(); 
     dd($posts_results); 
} 

請注意,您可以發送查詢作爲數據庫表(不是模型)的數組,如下所示:

$users = DB::table('posts')->where([ 
    ['visible', '=', '1'], 
    ['expire_date', '>', $current], 
    // ... 
])->get(); 
1

可以在query builder實例鏈中的where()功能:

$query = Post::where('visible', 1)->where('expire_date', '>', $current); 

if(!empty($termn)){ 
     $query->where('title', 'LIKE', '%'.$termn.'%') 
} 
if(!empty($request->input('category'))){ 
     $query->where('category_id', $input_category) 
} 
if(!empty($request->input('municipality_id'))) { 
     $query->where('municipality_id', $input_municipality) 
} 

$posts = $query->get();