Using COLLATE inside Doctrine DQL Query (Symfony2)

后端 未结 1 1017
梦谈多话
梦谈多话 2021-01-03 03:52

I can\'t find anything related to using COLLATE in a DQL query with Doctrine (and ofcourse it doesn\'t seem to work).

My specific problem:

I have a table wit

相关标签:
1条回答
  • 2021-01-03 04:37

    Following Cerad 's suggestion to write a custom DQL function: http://www.doctrine-project.org/2010/03/29/doctrine2-custom-dql-udfs.html

    I managed to create this:

    namespace MyCompany\MyBundle\DQL;
    
    use Doctrine\ORM\Query\AST\Functions\FunctionNode;
    use Doctrine\ORM\Query\Lexer;
    
    class CollateFunction extends FunctionNode
    {
        public $expressionToCollate = null;
        public $collation = null;
    
        public function parse(\Doctrine\ORM\Query\Parser $parser)
        {
            $parser->match(Lexer::T_IDENTIFIER);
            $parser->match(Lexer::T_OPEN_PARENTHESIS);
            $this->expressionToCollate = $parser->StringPrimary();
    
            $parser->match(Lexer::T_COMMA);
    
            $parser->match(Lexer::T_IDENTIFIER);
            $lexer = $parser->getLexer();
            $this->collation = $lexer->token['value'];
    
            $parser->match(Lexer::T_CLOSE_PARENTHESIS);
        }
    
        public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
        {
            return sprintf( '%s COLLATE %s', $this->expressionToCollate->dispatch($sqlWalker), $this->collation );
        }
    }
    

    When registered to the config.yml (http://symfony.com/doc/current/cookbook/doctrine/custom_dql_functions.html) This will look for a Collate 'function' with two arguments: a field and a charset (no valid charset detection yet).

    Works like (written in DQL)

    COLLATE( field , collation ) 
    

    And creates (in runable MySQL)

    `field` COLLATE collation 
    

    Ofcourse collation should be a valid charset (such as utf8_bin) or you will get a MySQL error.

    I guess there is a simpler solution, but I only could create this as a 'function'. At least the problem is solved.

    0 讨论(0)
提交回复
热议问题