我有这段代码
$arrayFilter = ['category' => $category,
'compartment' => $compartment,
'doors' => $doors,
'brand' => $brand,
'model' => $model,
'area' => $area,
'status'=> $status,
'fuel' => $fuel,
'speeds'=> $speeds,
'year' => $year];
$queryString = "";
foreach($arrayFilter as $filter => $val){
if (!empty($val)){
$queryString.= "['$filter', '=', '$val'], ";
}
}
echo $qString = mb_substr($queryString, 0, -2, 'UTF-8');
DB::table('Catalog')->where([$qString])->get();
并收到此错误
Connection.php第761行中的QueryException:
SQLSTATE [42S22]:未找到列:1054未知列' 0'在' where子句' (SQL:select * fromCatalog
where(0
=))
有什么问题?在编码或括号中。 $ queryString为空,但在它满时显示相同的错误。我无法理解这个问题。
答案 0 :(得分:1)
where()
的参数是数组。您创建字符串。为什么呢?
简单地:
$where = [];
foreach($arrayFilter as $filter => $val){
if (!empty($val)){
$where[] = [$filter, '=', $val];
}
}
DB::table('Catalog')->where($where)->get();
答案 1 :(得分:0)
将该数组$arrayFilter
直接传递给where
。它可以接受一个数组field => value
。
DB::table('Catalog')->where($arrayFilter)->get();
您的数组已经正确..比较运算符是可选的查询,默认为' =',不存在时。
['field' => 'value']
最终会成为:
... WHERE (`field` = ?)