gpt4 book ai didi

php - Laravel 5.2 - 带数组的过滤器

转载 作者:可可西里 更新时间:2023-11-01 13:27:30 24 4
gpt4 key购买 nike

我正在做一个搜索过滤器,我有 3 个输入“市政”、“类别”、“关键字”,如果输入不为空,我正在尝试将值插入数组。像这样:

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($filter) 返回如下: enter image description here

可能数组结构不对,我也试过这样: laravel 5.2 search query但它不起作用。没有 dd($filter) 我有这个错误:

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))

感谢您的帮助!

最佳答案

您错误地使用了 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);
}

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

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

关于php - Laravel 5.2 - 带数组的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com