Laravel 5.2 - 带阵列的过滤器

Die*_*des 6 php arrays laravel

我正在做一个搜索过滤器,我有3个输入"municipality","category","keyword",我试着插入值到数组IF输入不为空.像这样:

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();
}
Run Code Online (Sandbox Code Playgroud)

但它不能很好地过滤,dd($ filter)返回如下: 在此输入图像描述

也许数组的结构不好,我也试过这样: laravel 5.2搜索查询, 但它不起作用.没有dd($ filter)我有这个错误:

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误; 检查与您的MariaDB服务器版本对应的手册,以便在'附近使用正确的语法.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`...为null并且'municipality_id', '=', 1为null))

谢谢您的帮助!

Yah*_*din 1

您错误地使用了 where 子句。请参阅以下文档:

模型中 where 子句的选项应作为链式方法中的参数(而不是数组值)发送,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,您可以将查询作为数据库表(而不是模型)的数组发送,如下所示:

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