1

我正在使用 Symfony2 和教义 2,但这个查询有问题:

    $query = $em->createQuery('SELECT a FROM MyBundle:Artiste a WHERE a.id IN (4,12,1)');
    $result = $query->getArrayResult();

而且我总是按 a.id 获得结果顺序,即 1 然后 4 然后 12 而我想显示排序为 id 列表的结果:4 然后 12 然后 1。

更新 感谢@Bram Gerritsent 评论,我注册了一个自定义 DQL 函数 FIELD,所以这就是我所做的:

  1. 在 MyBundle/DQL/Field.php 中,我插入了以下代码(https://github.com/beberlei/DoctrineExtensions/blob/master/lib/DoctrineExtensions/Query/Mysql/Field.php)(我刚刚改变了要成为的命名空间namespace MyBundle\DQL;

  2. 然后,我在我的 config.yml 中添加以下内容,如 Symfony2 文档 ( http://symfony.com/doc/2.0/cookbook/doctrine/custom_dql_functions.html )中所示

    orm: auto_generate_proxy_classes: "%kernel.debug%" entity_managers: 默认: auto_mapping: true dql: string_functions: field: MyBundle\DQL\Field

  3. 所以,我写了以下查询 $query =$em->createQuery('SELECT a FROM MyBundle:Artiste a WHERE a.id IN (4,12,1) ORDER BY FIELD(4,12,1)');但我收到了这个错误:[Syntax Error] line 0, col 75: Error: Expected end of string, got '('

4

2 回答 2

5

You need to have a look into MySql FIELD function.

In native MySql you would do something like this:

ORDER BY FIELD(a.id,4,12,1)

The field function isn't part of the Doctrine 2 distribution, but you can get it from the DoctrineExtensions.

See this StackOverflow post for more information about using the FIELD function in Doctrine 2

EDIT

I have tested it using your query but got the same syntax error. The following query works for me. Not sure why you cannot use ORDER BY field(a.id,4,12,1) directly, but you have to create a HIDDEN field in your select first.

SELECT a, field(a.id,4,12,1) as HIDDEN field FROM MyBundle:Artiste a WHERE a.id IN (4,12,1) ORDER BY field

EDIT2

I have done some more debugging and researching and the DQL parser doesn't seem to support string functions in the order by clause. I've fixed the issue and created a Pull Request.

于 2013-03-05T09:11:57.270 回答
0

不如 FIELD 功能好,但应该可以工作:

  SELECT output.a FROM (
    SELECT a, ( CASE WHEN a.id = 4 THEN 1 WHEN a.id = 12 THEN 2 a.id = 1 THEN 3 END ) ord FROM MyBundle:Artiste a WHERE a.id IN (4,12,1)) output ORDER BY output.ord
于 2013-03-05T09:18:08.810 回答