2016-10-29 157 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();