我正在寻找一种创建忽略空格的学说查询的方法。我尝试用replace,但是我一直都收到
预期的已知功能,得到“替换”
我的查询看起来像:
$query = $em->createQueryBuilder(); $query->select('c') ->from('ACME\UserBudnle\Entity\User', 'c') ->where('replace(c.username," ","")'.' LIKE :searchName') ->setParameter('searchName', '%@' . $searchName. '%') ->orderBy('c.username', 'asc');
好的,我编写了一个替换DQL函数。
<?php namespace Acme\UserBundle\DQL; use Doctrine\ORM\Query\Lexer; use Doctrine\ORM\Query\AST\Functions\FunctionNode; /** * "REPLACE" "(" StringPrimary "," StringSecondary "," StringThird ")" */ class replaceFunction extends FunctionNode{ public $stringFirst; public $stringSecond; public $stringThird; public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { return 'replace('.$this->stringFirst->dispatch($sqlWalker) .',' . $this->stringSecond->dispatch($sqlWalker) . ',' .$this->stringThird->dispatch($sqlWalker) . ')'; } public function parse(\Doctrine\ORM\Query\Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); $this->stringFirst = $parser->StringPrimary(); $parser->match(Lexer::T_COMMA); $this->stringSecond = $parser->StringPrimary(); $parser->match(Lexer::T_COMMA); $this->stringThird = $parser->StringPrimary(); $parser->match(Lexer::T_CLOSE_PARENTHESIS); } }
接下来在app / config.yml中,我添加:
doctrine: orm: auto_generate_proxy_classes: "%kernel.debug%" auto_mapping: true dql: string_functions: replace: Acme\UserBundle\DQL\replaceFunction
最后,我在控制器中创建了一个DQL查询:
$em = $this->getDoctrine()->getManager(); $query = $em->createQueryBuilder(); $query->select('u') ->from('Acme\UserBundle\Entity\User', 'u') ->where("replace(u.username,' ','') LIKE replace(:username,' ','') ") ->setParameter('username', '%' . $usernameForm . '%') ->orderBy('u.username', 'asc'); $result = $query->getQuery()->getResult();
最有趣的是,“引号”非常重要。这意味着您可以在select,from,setParameter和orderB中看到,我使用’‘,但在其中使用“”和space”。相反的是行不通的。我不知道为什么。