【问题标题】:doctrine2: how to use the random custom function?教义2:如何使用随机自定义功能?
【发布时间】:2014-02-28 13:22:43
【问题描述】:

我在 symfony2 框架中使用了学说。我想选择单个随机字段。 我不想使用本机查询或使用 PHP 随机获取。

我试着按照

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html

https://gist.github.com/Ocramius/919465

config.yml中连接的扩展函数

orm:
    ...
    entity_managers:
        default:
            ...

            dql:
                numeric_functions:
                    rand: MyProject\MyBundle\DQL\Rand

我尝试在控制器中调用查询

    $product= $em->createQueryBuilder('p')
                 ->select('w')
                 ->from('MyBundle:Product', 'p')
                // ->orderBy('RAND ()') // I tried so
                 ->addSelect('RAND() as HIDDEN rand') // and so
                 ->orderBy('rand')
                 ->getQuery()
                 ->getSingleResult();

我也试过了

       $product = $em->createQuery('SELECT p FROM MyBundle:Product p ORDER BY RAND()')
                     ->setMaxResults(1)
                     ->getSingleResult();

我得到错误:

           Error: Expected end of string, got '(' 

请注意,“ASC”在查询中的“RAND()”之后。 我尝试调用 orderBy('RAND()', ''),但没有成功...

【问题讨论】:

标签: symfony doctrine-orm dql


【解决方案1】:

使用此捆绑包:https://github.com/mapado/MysqlDoctrineFunctions

您可以在 DQL 查询中使用这些函数:

$query = 'SELECT RAND(), ROUND(123.45) 
    FROM ...
';

$em->createQuery($query);

但是你不能使用->orderBy...

4.8.2。我可以在 DQL 中按函数(例如 ORDER BY RAND())排序吗?

不,不支持在 DQL 中按功能排序。如果您需要此功能,您应该使用本机查询或提出其他解决方案。附带说明:从 1000 行开始,使用 ORDER BY RAND() 进行排序非常缓慢。

http://docs.doctrine-project.org/en/2.1/reference/faq.html#can-i-sort-by-a-function-for-example-order-by-rand-in-dql

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2018-10-23
    相关资源
    最近更新 更多