Skip to content Skip to sidebar Skip to footer

Doctrine Query - Ignoring Spaces

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:

Solution 1:

Ok I write a replace DQL Function.

<?phpnamespaceAcme\UserBundle\DQL;

useDoctrine\ORM\Query\Lexer; 
useDoctrine\ORM\Query\AST\Functions\FunctionNode; 


/**
 * "REPLACE" "(" StringPrimary "," StringSecondary "," StringThird ")"
 */classreplaceFunctionextendsFunctionNode{

    public$stringFirst; 
    public$stringSecond; 
    public$stringThird; 


    publicfunctiongetSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) {
        return'replace('.$this->stringFirst->dispatch($sqlWalker) .','
                . $this->stringSecond->dispatch($sqlWalker) . ',' 
                .$this->stringThird->dispatch($sqlWalker) . ')';
    }

    publicfunctionparse(\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:truedql: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.

Post a Comment for "Doctrine Query - Ignoring Spaces"