This question already has an answer here:
-
Expected known function, got 'MD5'
1 answer
I`m looking for a way to create a doctrine query with ignoring spaces.
I try with replace but I receive all the time
Expected known function, got 'replace'
My query look like:
$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');
Ok I write a replace DQL Function.
<?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);
}
}
Next in app/config.yml I add:
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
dql:
string_functions:
replace: Acme\UserBundle\DQL\replaceFunction
And finally I create a DQL query in my Controller:
$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();
The most funny thing is that "quotes" are very important. It means that you can see that in select, from, setParameter and orderBy I use '' but in where I use "" and space ''. The opposite is not working. I don`t know why.