我正在做一个搜索过滤器,我有3个输入"市政","类别","关键字",我' m尝试将值插入数组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();
}
也许数组的结构不行,我也试过这样: laravel 5.2 search query 但它不起作用。 没有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`.
附近使用正确的语法。.
为空,'municipality_id', '=', 1
为空))
感谢您的帮助!
答案 0 :(得分:1)
您可以将where()
实例中的query builder
函数链接为:
$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();
答案 1 :(得分:1)
您使用的where子句错误。请参阅以下文档:
模型中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();