Symfony 和 Doctrine DQL 查询生成器:如果条件检查,如何在内部使用多个 setParameters?

Symfony and Doctrine DQL query builder: how to use multiple setParameters inside if condition checks?

将 Symfony 和 Doctrine 与 DQL 查询构建器一起使用,我需要选择性地添加一些带参数的 WHERE 条件,以及一些 if 条件检查。

伪代码示例:

$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,
        ]);
}

出现如下错误:

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

到目前为止我发现的解决这个问题的最干净的方法是将所有参数包装在一个数组中,然后只调用一次 setParameters() 方法,检查是否至少有一个参数要设置:

$qb = $this->getEntityManager()->createQueryBuilder();
$qb = $qb
    ->select('SOMETHING')
    ->from('SOMEWHERE')
    ->where('SOME CONDITIONS')

$parameters = [];

if ( SOME CHECK ) {
    $qb
        ->andWhere('field1 = :field1')
        ->andWhere('field2 = :field2');

    $parameters['field1'] = $myFieldValue1;
    $parameters['field2'] = $myFieldValue2;

} else {
    $qb->andWhere('field1 = :field1');
    $parameters['field1'] = $myOtherFieldValue1;
}

if (count($parameters)) {
    $qb->setParameters($parameters);
}

可以一一设置参数:

$qb
    ->setParameter('field1', $value1)
    ->setParameter('field2', $value2);

这样您就可以确保不会用 setParameters 覆盖其他参数。