Reputation: 2417
I have dynamic where conditions. They consist of the following array:
array:2 [
"brand_name" => array:2 [
0 => "a"
1 => "b"
]
"category_type" => array:1 [
0 => "AA"
]
]
I need to apply where conditions to my query.
$em = $this->getEntityManager();
$sql = " select * from products as p";
$i = 0;
foreach ($wheres as $key => $value) {
if ($i === 0) {
$sql .= " WHERE";
} else {
$sql .= " AND";
}
$sql.= " te.$key IN (:$key)";
$i +=1;
}
I am not sure how to assign the value to the query. If I had single where condition, I did something like this:
$params = array(
$ids,
);
$query = $em->getConnection()->executeQuery(
$sql,
$params,
array(
\Doctrine\DBAL\Connection::PARAM_STR_ARRAY,
\PDO::PARAM_INT,
)
);
$records = $query->fetchAll();
But I don't know how to fix where where conditions are in dynamic.
Upvotes: 2
Views: 184
Reputation: 47308
This is very easy using the query builder. It's the kind of thing it was designed for.
Something like this would take you there:
$qb = $this->createQueryBuilder('p');
$suffix = 0;
foreach ($conditions as $key => $value) {
$parameter = 'query_' . $suffix++;
$qb->andWhere("p.$key IN :$parameter")
->setParamter($parameter, $value);
}
$records = $qb->getQuery()->getResult()
You'll need to make adjustments to suit your data model. In your question you are selecting products as p
, but then you are trying to select from te
, so I guess some pieces are missing from the puzzle.
But you should be able to finish it from here.
Upvotes: 3