Issue
I need to write a query with multiple where condition and OR condition. This OR condition is only when if $location array is not empty. So parameters are needed only when this array is not empty.
I am not sure how to write this parameter condition in this condition.
This is the query I am working on.
$qb = $this->createQueryBuilder("e")
->select(
"e.vehicleId",
"e.schemaId",
"e.location",
)
->andWhere("e.vehicleId = :vehicleId")
->andWhere("e.optionId = :optionId")
->andWhere("e.schemaId = :schemaId");
if (count($position) > 0) {
$qb->andWhere($qb->expr()->orX(
$qb->expr()->andX("e.location = :location"),
$qb->expr()->andX("e.location = :loc")
));
}
$qb->setParameters(array(
"vehicleId" => $vehicleId,
"schemaId" => $schemaId,
"location" => $position["location"],
"loc" => $position["loc"],
));
Solution
QueryBuilder has two methods to set the query parameters.
The one you are using (setParameters(array $parameters), and the simpler setParameter($parameterName, $parameterValue).
Use the latter instead of the one you are using, and you can set the parameter where you need it:
if (count($position) > 0) {
$qb->andWhere($qb->expr()->orX(
$qb->expr()->andX("e.location = :location"),
$qb->expr()->andX("e.location = :loc")
))
->setParameter('location', $position["location"])
->setParameter('loc', $position["loc"]);
}
Answered By - yivi
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.