QueryBuilder Symfony2 参数
QueryBuilder Symfony2 Parameters
大家好,我想制作下面解释的简单查询生成器,但我无法更改添加字符串以通过参数发送它们。
我喜欢,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
对于参数绑定,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()
;
大家好,我想制作下面解释的简单查询生成器,但我无法更改添加字符串以通过参数发送它们。
我喜欢,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
对于参数绑定,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()
;