Reputation: 11
I've this code
$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();
and receive this error
QueryException in Connection.php line 761:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * fromCatalog
where (0
= ))
What is the problem? In the encoding or in the brackets. $queryString is empty, but it shows the same error when it's full. I can't understand the problem.
Upvotes: 1
Views: 1034
Reputation: 50491
Just pass that array $arrayFilter
directly to where
. It can accepts an array as field => value
already.
DB::table('Catalog')->where($arrayFilter)->get();
Your array is correct already .. the comparison operator is optional with querying and defaults to '=', when not present.
['field' => 'value']
Will end up being:
... WHERE (`field` = ?)
Upvotes: 0
Reputation: 54841
Argument to where()
is array. You create a string. Why?
Simply:
$where = [];
foreach($arrayFilter as $filter => $val){
if (!empty($val)){
$where[] = [$filter, '=', $val];
}
}
DB::table('Catalog')->where($where)->get();
Upvotes: 1