Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using wildcards with Doctrine's createQuery method

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?

like image 589
Joseph Woodward Avatar asked Jan 20 '13 02:01

Joseph Woodward


1 Answers

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

like image 114
Pete Mitchell Avatar answered Sep 22 '22 16:09

Pete Mitchell