使用Doctrine QueryBuilder忽略参数

时间:2016-11-25 12:52:16

标签: php symfony doctrine query-builder

我有一堆包含参数的过滤器,我希望使用Doctrine中的QueryBuilder将其包含在我的查询中。

这是我的代码:

$qb=  $em->createQueryBuilder();
$query_qb = $qb
     ->from('padmaxResilieBundle:Subscriber','s')
     ->leftjoin('s.terminationPaper','l')
     // ...
     ->leftjoin('c.cancelreasons','cr');

    if ($filters) {
        foreach ($filters as $value) {
            $query_qb->andWhere($value);
        }
    }

    $query_qb->setParameters($this->paramsMap);

     $total = $query_qb->addSelect('COUNT(DISTINCT s)')
         ->getQuery()
         ->getResult();

数组$ filters的每个元素都是带有1个或多个参数出现的字符串,例如:

$filters = array(
    0 => "s.lastname LIKE '%:param1%' OR s.firstname LIKE '%:param1%'"
    1 => "c.contractNumber LIKE '%:param2%'"
    // ...
)

每个过滤器的参数标识符都不同,并在属性paramMap中引用,如:

$this->paramMap = array(
    "param1" => "my_value",
    "param2" => "hello",
    // ...
)

我确信过滤器数组和paramMap都是正确的并互相引用,但我总是得到错误:

Invalid parameter number: number of bound variables does not match number of tokens

我无法确定我做错了什么,有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您不能像以前那样在字符串中使用参数:

"c.contractNumber LIKE '%:param2%'"

您需要在参数中添加%字符:

$filters = array(
    0 => "s.lastname LIKE :param1 OR s.firstname LIKE :param1"
    1 => "c.contractNumber LIKE :param2"
    // ...
)

$this->paramMap = array(
    "param1" => "%my_value%",
    "param2" => "%hello%",
    // ...
)