'How to remove parameters from query builder?
I have a problem with my query builder. I am using symfony. What i want to acomplish: I have a given query builder, and i want to count all rows based on this query. So i worked on following solution:
$aliases = $queryBuilder->getRootAliases();
$alias = array_values($aliases)[0];
$cloneQueryBuilder = clone $queryBuilder;
$from = $cloneQueryBuilder->getDQLPart('from');
$cloneQueryBuilder->resetDQLParts();
$newQueryBuilder = $cloneQueryBuilder
->select('count(' . $alias . '.id)')
->add('from', $from[0]);
$this->total = $newQueryBuilder->getQuery()->getSingleScalarResult();
However im getting an exception : Too many parameters: the query defines 0 parameters and you bound 1 Does anyone knows how to solve it ?
Solution 1:[1]
Calling setParameters should overwrite all existing parameters.
Solution 2:[2]
As \Doctrine\ORM\QueryBuilder::$parameters is type of ArrayCollection, you can just call clear or removeElement on it.
$builder->getParameters()->removeElement(
$builder->getParameter('specificParameter')
);
$builder->getParameters()->clear();
more about ArrayCollection - https://www.doctrine-project.org/projects/doctrine-collections/en/1.6/index.html
Solution 3:[3]
I don't believe the above answer is correct. As you can see, setParameters only updates the existing parameters. It does not remove any which are already set:
http://www.doctrine-project.org/api/orm/2.2/source-class-Doctrine.ORM.QueryBuilder.html#354
The solution I found was to iterate through the existing parameters and set each value to null.
foreach($queryBuilder->getParameters() as $key=>$value){
$queryBuilder->setParameter($key,null);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joshua |
| Solution 2 | Jok?bas |
| Solution 3 | Aaron Lozier |
