Can anyone enlighten me as to why this query isn't working please? I tried alternating between single and double quotes as well.
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT t FROM AcmeBlogBundle:BlogTag t WHERE t.title LIKE \'%:title%\'')
->setParameter('title', $keyword);
Doctrine simply returns Invalid parameter number: number of bound variables does not match number of tokens
.
Also, is it better to perform such a query using the createQuery method or createQueryBuilder?
PDO treats both the keyword and the % wildcards as a single token. You cannot add the wildcards next to the placeholder. You must append them to the string when you bind the params.
Also see this comment on the php docs.
Therefore you will need to do the following:
$qb = $em->createQueryBuilder();
$qb
->select('tag')
->from('AcmeBlogBundle:BlogTag', 'tag')
->where($qb->expr()->like('tag.title', ':title'))
->setParameter('title', '%' . $keyword . '%')
;
or
$query = $em->createQuery('SELECT t FROM AcmeBlogBundle:BlogTag t WHERE t.title LIKE :title');
$query->setParameter('title', '%' . $keyword . '%');
I prefer to use the query builder because it is nicer for structuring and making your statement more maintainable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With