Symfony2 createQuery order by field

不羁的心 提交于 2019-12-12 11:23:33

问题


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.



来源:https://stackoverflow.com/questions/19867118/symfony2-createquery-order-by-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!