Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 createQuery order by field

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?

like image 729
Lukas Lukac Avatar asked Nov 08 '13 19:11

Lukas Lukac


1 Answers

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
");
like image 164
Bram Gerritsen Avatar answered Oct 07 '22 07:10

Bram Gerritsen