【问题标题】:QueryBuilder Symfony2 ParametersQueryBuilder Symfony2 参数
【发布时间】:2016-06-08 13:27:12
【问题描述】:

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

我喜欢,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

【问题讨论】:

    标签: symfony orm doctrine query-builder dql


    【解决方案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()
    ;
    

    【讨论】:

      猜你喜欢
      • 2016-04-18
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多