Symfony2 createQuery order by field

2019-06-21 18:34发布

问题:

Hi i have this query writen in phpmyadmin and it works gr8.

SELECT u.* FROM users AS u WHERE
        u.id = 14469 OR
        u.id = 685

        ORDER BY u.id, field(u.id, 14469, 685)

But i need to write it in symfony2. How it will looks like? Because this is throwing me an error:

    $query=$this->_em->createQuery("SELECT u FROM UserBundle:User u WHERE
        u.id = 14469 OR
        u.id = 685

        ORDER BY u.id, field(u.id, 14469, 685)
    ");

An exception has been thrown during the rendering of a template ("[Syntax Error] line 0, col 122: Error: Expected end of string, got '('")

Or its not allowed and i have to install and use some doctrine extension?

回答1:

The FIELD() function is MySQL specific and therefore not part of the Doctrine 2 library. You can use a custom DQL function, which is already created by the lead developer of Doctrine (Benjamin Eberlei). https://github.com/beberlei/DoctrineExtensions/.

Also I'm pretty sure you need to define the FIELD() function as hidden because you can't use functions in the order by in DQL. Marking it as hidden will prevent the function output to be hydrated in the resultset. Something in the line of:

$query=$this->_em->createQuery("SELECT u, field(u.id, 14469, 685) as HIDDEN field FROM UserBundle:User u WHERE
    u.id = 14469 OR
    u.id = 685
    ORDER BY u.id, field
");


回答2:

You can use "index by" to return a result indexed by your entity id. Then you only have to loop over your ordered array, and pick the right entity in the results.