学说2 dql,在进行类似比较时使用带有 % 通配符的 setParameter [英] doctrine2 dql, use setParameter with % wildcard when doing a like comparison

查看:29
本文介绍了学说2 dql,在进行类似比较时使用带有 % 通配符的 setParameter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用参数占位符 - 例如?1 - 带有 % 通配符.也就是说,类似于:u.name LIKE %?1%"(尽管这会引发错误).文档有以下两个示例:1.

I want to use the parameter place holder - e.g. ?1 - with the % wild cards. that is, something like: "u.name LIKE %?1%" (though this throws an error). The docs have the following two examples: 1.

// Example - $qb->expr()->like('u.firstname', $qb->expr()->literal('Gui%'))
public function like($x, $y); // Returns ExprComparison instance

我不喜欢这样,因为没有防止代码注入的保护.

I do not like this as there is no protection against code injection.

2.

// $qb instanceof QueryBuilder

// example8: QueryBuilder port of: "SELECT u FROM User u WHERE u.id = ?1 OR u.nickname LIKE ?2 ORDER BY u.surname DESC" using QueryBuilder helper methods
$qb->select(array('u')) // string 'u' is converted to array internally
   ->from('User', 'u')
   ->where($qb->expr()->orx(
       $qb->expr()->eq('u.id', '?1'),
       $qb->expr()->like('u.nickname', '?2')
   ))
   ->orderBy('u.surname', 'ASC'));

我不喜欢这样,因为我需要在对象的属性中搜索术语——也就是说,我需要两边的通配符.

I do not like this because I need to search for terms within the object's properties - that is, I need the wild cards on either side.

推荐答案

在将参数绑定到查询时,DQL 的工作方式与 PDO 几乎完全一样(这是 Doctrine2 在后台使用的).

When binding parameters to queries, DQL pretty much works exactly like PDO (which is what Doctrine2 uses under the hood).

因此,在使用 LIKE 语句时,PDO 将关键字和 % 通配符视为单个标记.您不能在占位符旁边添加通配符.绑定参数时必须将它们附加到字符串中.

So when using the LIKE statement, 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.

$qb->expr()->like('u.nickname', '?2')
$qb->getQuery()->setParameter(2, '%' . $value . '%');

请参阅 PHP 手册中的此评论.希望有所帮助.

See this comment in the PHP manual. Hope that helps.

这篇关于学说2 dql,在进行类似比较时使用带有 % 通配符的 setParameter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆