我正在使用Doctrine 2(更精确地说是Doctrine ORM 2.1)与MySQL,并且想要查找以数字开头的条目。使用本地SQL我会写类似以下的代码:
SELECT * FROM table WHERE name RLIKE '^[0-9]';
但是当我尝试使用DQL时,我遇到了以下错误:
[Syntax Error] line 0, col 71: Error: Expected =, <, <=, <>, >, >=, !=, got 'RLIKE'
#0 .../Doctrine/ORM/Query/Parser.php(396): Doctrine/ORM/Query/QueryException::syntaxError('line 0, col 73:...')
#1 .../Doctrine/ORM/Query/Parser.php(2746): Doctrine/ORM/Query/Parser->syntaxError('=, <, <=, <>, >...')
#2 .../Doctrine/ORM/Query/Parser.php(2533): Doctrine/ORM/Query/Parser->ComparisonOperator()
#3 .../Doctrine/ORM/Query/Parser.php(2071): Doctrine/ORM/Query/Parser->ComparisonExpression()
#4 .../Doctrine/ORM/Query/Parser.php(1994): Doctrine/ORM/Query/Parser->SimpleConditionalExpression()
#5 .../Doctrine/ORM/Query/Parser.php(1953): Doctrine/ORM/Query/Parser->ConditionalPrimary()
#6 .../Doctrine/ORM/Query/Parser.php(1927): Doctrine/ORM/Query/Parser->ConditionalFactor()
#7 .../Doctrine/ORM/Query/Parser.php(1899): Doctrine/ORM/Query/Parser->ConditionalTerm()
#8 .../Doctrine/ORM/Query/Parser.php(1218): Doctrine/ORM/Query/Parser->ConditionalExpression()
#9 .../Doctrine/ORM/Query/Parser.php(769): Doctrine/ORM/Query/Parser->WhereClause()
#10 .../Doctrine/ORM/Query/Parser.php(738): Doctrine/ORM/Query/Parser->SelectStatement()
#11 .../Doctrine/ORM/Query/Parser.php(210): Doctrine/ORM/Query/Parser->QueryLanguage()
#12 .../Doctrine/ORM/Query/Parser.php(281): Doctrine/ORM/Query/Parser->getAST()
#13 .../Doctrine/ORM/Query.php(203): Doctrine/ORM/Query/Parser->parse()
#14 .../Doctrine/ORM/Query.php(223): Doctrine/ORM/Query->_parse()
#15 .../Doctrine/ORM/AbstractQuery.php(586): Doctrine/ORM/Query->_doExecute()
#16 .../Doctrine/ORM/AbstractQuery.php(392): Doctrine/ORM/AbstractQuery->execute(Array, 1)
我尝试的是这样的:
$regex = '^[0-9]';
$em
->createQuery('
SELECT t
FROM MyEntity t
WHERE t.visible = true
AND t.name RLIKE ?1
ORDER BY t.name ASC')
->setParameter(1, $regex)
->getResult();
并且,这样一来:
$regex = '^[0-9]';
$em
->createQueryBuilder()
->select('t')
->from('MyEntity', 't')
->where('t.visible = true')
->andWhere(new Doctrine\ORM\Query\Expr\Comparison('t.name', 'RLIKE', '?1'))
->orderBy('t.name', 'ASC')
->getQuery()
->setParameter(1, $regex)
->getResult();
你有没有想过如何在DQL中使用RLIKE?
最好的问候 ;)