这是我查询数据库中一些单词的方法
Here is how I query my database for some words
$query = $qb->select('w')
->from('DbEntitiesEntityWord', 'w')
->where('w.indictionary = 0 AND w.frequency > 3')
->orderBy('w.frequency', 'DESC')
->getQuery()
->setMaxResults(100);
我正在使用 mysql,我想获得符合条件的随机行,我将在查询中使用 rand() 排序.
I'm using mysql and I'd like to get random rows that match the criteria, I would use order by rand() in my query.
我发现了这个类似的问题,这基本上表明,因为 ORDER BY RAND 不受支持在学说中,您可以改为随机化主键.但是,在我的情况下无法做到这一点,因为我有一个搜索条件和一个 where 子句,因此并非每个主键都满足该条件.
I found this similar question which basically suggests since ORDER BY RAND is not supported in doctrine, you can randomize the primary key instead. However, this can't be done in my case because I have a search criteria and a where clause so that not every primary key will satisfy that condition.
我还发现了一个 代码片段,建议您使用 OFFSET 来随机化行像这样:
I also found a code snippet that suggests you use the OFFSET to randomize the rows like this:
$userCount = Doctrine::getTable('User')
->createQuery()
->select('count(*)')
->fetchOne(array(), Doctrine::HYDRATE_NONE);
$user = Doctrine::getTable('User')
->createQuery()
->limit(1)
->offset(rand(0, $userCount[0] - 1))
->fetchOne();
我有点困惑,这是否会帮助我解决在我的情况下不支持随机排序的问题.我无法在 setMaxResult 之后添加偏移量.
I'm a little confused as to whether this will help me work around the lack of support for order by random in my case or not. I was not able to add offset after setMaxResult.
知道如何做到这一点吗?
Any idea how this can be accomplished?
Doctrine 团队 不愿意实现此功能.
The Doctrine team is not willing to implement this feature.
有多种解决方案可以解决您的问题,每种方法都有自己的缺点:
There are several solutions to your problem, each having its own drawbacks:
WHERE x.id IN(?)
加载关联的对象.ORDER BY RAND()
之外的其他原始 SQL 技术,我不会在此详细说明),你会在这个网站上找到一些很好的资源).WHERE x.id IN(?)
to load the associated objects, by passing the array of IDs as a parameter.ORDER BY RAND()
exist, I won't detail them here, you'll find some good resources on this website).这篇关于如何用学说随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!