Answer the question
In order to leave comments, you need to log in
How to build a query for a filter with complex conditions in the doctrine?
I'm filtering a directory. It has a lot of options for filtering, a simplified line looks something like this
/[email protected]=1&[email protected]=2015|2019&[email protected]=>&[email protected]=красный|синий&[email protected]=bmw|honda
public function buildQuery(QueryBuilder $qb): QueryBuilder
{
[$normalizedKey] = $this->getKeys($qb); //значение вместе с алиасом
if ($this->getFrom()) {
$qb->andWhere($qb->expr()->andX(
$qb->expr()->gte($normalizedKey, $this->getFrom())
));
}
if ($this->getTo()) {
$qb->andWhere($qb->expr()->andX(
$qb->expr()->lte($normalizedKey, $this->getTo())
));
}
return $qb;
}
public function buildQuery(QueryBuilder $qb): QueryBuilder
{
[$normalizedKey, $key] = $this->getKeys($qb);
$values = $this->getValue();
$qb->andWhere($normalizedKey . ' IN (:values)')->setParameter('values', $values, Connection::PARAM_STR_ARRAY);
return $qb;
}
"SELECT c FROM App\Entity\Car c WHERE c.isStock = :isStock AND c.year >= 2015 AND c.year <= 2019 AND c.color IN (:values) AND c.brand IN (:values)"
Answer the question
In order to leave comments, you need to log in
In a loop for different filters, you add parameters with one key to one QueryBuilder object values
, then when assembling the query, Doctrine gets the first Parameter found with a key values
(and there are several of them, but the first one is enough for it).
Doctrine code:
That is, for color, year, level - the first parameter with the key is always taken. I values
suggest to substitute a different alias instead of this word, for example key:
[$normalizedKey, $key] = $this->getKeys($qb);
$qb
->andWhere(sprintf('%s IN (:%s)', $normalizedKey, $key))
->setParameter($key, $this->getValue());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question