Hello guys I want to make simple query builder explained below, but I can't change adding string to send them through parameters.
I've like, 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()
;
}
It's running excellent, but!
I want:
$qb->expr()->like('o.title', $qb->expr()->literal('%'.$query['text'].'%')),
To be:
$qb->expr()->like('o.title', $qb->expr()->literal('%:text%')),
or
$qb->expr()->like('o.title', $qb->expr()->literal('%?2%')),
But error occurs
Too many parameters: the query defines 1 parameters and you bound 2
For parameters binding, DQL pretty much works exactly like PDO .
Try this :
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()
;