在Doctrine的createQuery方法中使用通配符

时间:2013-01-20 02:41:26

标签: symfony doctrine

有人可以告诉我为什么这个查询不起作用吗?我也试过在单引号和双引号之间交替。

$em = $this->getDoctrine()->getManager();

$query = $em->createQuery('SELECT t FROM AcmeBlogBundle:BlogTag t WHERE t.title LIKE \'%:title%\'')
->setParameter('title', $keyword);

Doctrine只返回Invalid parameter number: number of bound variables does not match number of tokens

此外,使用createQuery方法或createQueryBuilder执行此类查询是否更好?

1 个答案:

答案 0 :(得分:25)

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

另请参阅php docs上的this comment

因此,您需要执行以下操作:

$qb = $em->createQueryBuilder();

$qb
    ->select('tag')
    ->from('AcmeBlogBundle:BlogTag', 'tag')
    ->where($qb->expr()->like('tag.title', ':title'))
    ->setParameter('title', '%' . $keyword . '%')
;

$query = $em->createQuery('SELECT t FROM AcmeBlogBundle:BlogTag t WHERE t.title LIKE :title');
$query->setParameter('title', '%' . $keyword . '%');

我更喜欢使用查询构建器,因为它更适合于构造并使您的语句更易于维护

相关问题