QueryBuilder Symfony2参数

时间:2016-02-25 16:28:57

标签: symfony orm doctrine query-builder dql

大家好我想在下面解释一下简单的查询构建器,但我无法更改添加字符串以通过参数发送它们。

我喜欢,OpinionRepository

public function search(array $query)
{
    $qb = $this->_em->createQueryBuilder();

    return $qb
        ->select('o')
        ->from('AppBundle:Opinion', 'o')
        ->join('o.category', 'c')
        ->where('c.id = ?1')
        ->andWhere(
            $qb->expr()->orX(
                $qb->expr()->like('o.title', $qb->expr()->literal('%'.$query['text'].'%')),
                $qb->expr()->like('o.text', $qb->expr()->literal('%'.$query['text'].'%'))
            )
        )
        ->setParameters([
            1 => $query['categoryId']
        ])
        ->getQuery()
        ->getResult()
    ;
}

它运行良好,但是!

我想:

$qb->expr()->like('o.title', $qb->expr()->literal('%'.$query['text'].'%')),

成为:

$qb->expr()->like('o.title', $qb->expr()->literal('%:text%')),

$qb->expr()->like('o.title', $qb->expr()->literal('%?2%')),

但是发生了错误

Too many parameters: the query defines 1 parameters and you bound 2

1 个答案:

答案 0 :(得分:1)

对于参数绑定,DQL与PDO完全相同。

试试这个:

return $qb
    ->select('o')
    ->from('AppBundle:Opinion', 'o')
    ->join('o.category', 'c')
    ->where('c.id = ?1')
    ->andWhere(
        $qb->expr()->orX(
            $qb->expr()->like('o.text', '?2'),
            $qb->expr()->like('o.title', '?2'),
        )
    )
    ->setParameters(array(
        1 => $query['categoryId'],
        2 => '%'.$query['text'].'%',
    ))
    ->getQuery()
    ->getResult()
;