如何通过Doctrine2 querybuilder获取随机行? [英] How to fetch random row via Doctrine2 querybuilder?

查看:119
本文介绍了如何通过Doctrine2 querybuilder获取随机行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有:

$qb1 = $this->getEntityManager()->createQueryBuilder();
            $qb1->select('s')
                ->from('\My\Entity\Song', 's')
                ->where('s.id <> ?1')
                ->orderBy('RAND()', '')
                ->setMaxResults(1)
                ->setParameters(array(1=>$current->id));

但是doctrine2不明白:

But doctrine2 doesn't understand that:

Error: Expected end of string, got '('

甚至没有他们的querybuilder页面有什么,你想告诉我,php最好的ORM没有随机函数?

Not even their querybuilder page has anything on it. Do you want to tell me that the best ORM for php doesn't have a random function?

推荐答案

orderBy方法应该接受Song的字段进行排序(例如's.author'或's.title'),而不是随机值,即使您选择了一个随机字段进行排序,例如在php中随机选择一个,这根本不是很随机,因为你总是会获得当前排序标准的第一个结果,如果你的歌曲有8个字段,那么你的搜索中只能收到8首歌曲

The orderBy method should accept a field of Song for sorting purposes (such as 's.author' or 's.title'), and not a random value. Even if you chose a random field for ordering, such as selecting one randomly in php, this will not be very random at all, because you are always going to get the first result for the current sort criteria. If your songs have 8 fields, you would only get 8 different songs in your search results ever, even if you have thousands stored.

这是一个建议:

$qb1->select('s')
    ->from('\My\Entity\Song', 's')
    ->where('s.id <> ?1')
    ->setMaxResults(1)
    ->setParameters(array(1=>$current->id))
    ->setFirstResult($offset);

这里,$ offset可以是通过rand()或mt_rand()获取的PHP中的随机值,功能。当然,$ offset应该比总歌曲小。这只是一个建议,有很多方法可以实现这一点。

Here, $offset can be a random value you obtain in php via rand() or mt_rand() functions. Of course, $offset should be smaller than the total number of songs. This is just a suggestion, there are many ways you can accomplish this.

我认为Doctrine2是一个非凡的ORM,没有什么像这样高级的。我假设您阅读了参考指南的查询生成器部分,但我也建议您阅读 DQL 部分,这说明了Doctrine查询系统中可用的功能是什么,以及如何制作自己的(!)。

IMHO I think Doctrine2 is an extraordinary ORM, and there is nothing so advanced like it. I assume you read the Query Builder section of the reference guide, but I also suggest you read the DQL section, which explains what are the available functions within Doctrine query system, and how you can make your own (!).

这篇关于如何通过Doctrine2 querybuilder获取随机行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆