Using Symfony and Doctrine with the DQL query builder, I need to optionally add some WHERE conditions with parameters, with some if condition checks.
Pseudo code example:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb = $qb
->select('SOMETHING')
->from('SOMEWHERE')
->where('SOME CONDITIONS');
if ( SOME CHECK ) {
$qb
->andWhere('field1 = :field1')
->andWhere('field2 = :field2')
->setParameters([
'field1' => $myFieldValue1,
'field2' => $myFieldValue2,
]);
} else {
$qb
->andWhere('field1 = :field1')
->setParameters([
'field1' => $myOtherFieldValue1,
]);
}
Getting errors like:
Invalid parameter number: number of bound variables does not match number of tokens
Too few parameters: the query defines X parameters but you only bound Y
Too many parameters: the query defines X parameters and you bound Y