Doctrine querybuilder如何用参数数组替换参数?

时间:2017-05-10 10:17:11

标签: php symfony doctrine-orm

我想用参数数组替换一些参数,因为我不知道会收到多少变量。 问题是我的函数返回了一些与我的原始数组不对应的结果......这就是逻辑。我不知道该怎么做。

我需要通过$filter而不是$filter$filter2$filter3的数组来转换此函数。

public function getContentByFilterTest($categ,$filter,$filter2,$filter3){
    $query = $this->createQueryBuilder('c')
    ->join('c.filterfilter', 'f1')
    ->join('c.filterfilter', 'f2')
    ->join('c.filterfilter', 'f3')
    ->andWhere('f1.idfilter = :filter_idfilter1')
    ->andWhere('f2.idfilter = :filter_idfilter2')
    ->andWhere('f3.idfilter = :filter_idfilter3')
    ->andWhere('c.contentCategorycontentCategory = :category')
    ->setParameters(array(
            'filter_idfilter1' => $filter,
            'filter_idfilter2' => $filter2,
            'filter_idfilter3' => $filter3,
            'category' => $categ,
    ))
    ->getQuery()->getResult();
    return $query;
}

我试过了:

public function getContentByFilterTestBoucle($categ, array $filters ){
    $query = $this->createQueryBuilder('c')->select('c.name');
    for ($i = 1; $i <= count($filters); $i++){
        $query = $query->join('c.filterfilter', 'f'.$i)
        ->andWhere('f'.$i.'.idfilter = :filter_idfilter'.$i)
        ->setParameters(array(
                'filter_idfilter'.$i => $filters[$i-1],
        ))
        ;
    }
    $query->andWhere('c.contentCategorycontentCategory = :category')
    ->setParameter('category', $categ)
    ->getQuery()->getResult();
    return $query;
}

1 个答案:

答案 0 :(得分:3)

setParameters替换所有先前设置的参数,因此你应该使用它:

    ->setParameter(
            sprintf('filter_idfilter%s',$i) , $filters[$i-1]
    )

而不是:

    ->setParameters(array(
            'filter_idfilter'.$i => $filters[$i-1],
    ))

希望这个帮助