【发布时间】:2017-02-17 11:34:32
【问题描述】:
如何使用 dql 查询获得随机结果?
这是我的查询:
$firstCategoryId = 50;
$repository = $this->entityManager->getRepository(BaseProduct::class);
$products = $repository->createQueryBuilder('p')
->join('p.categories', 'c')
->where('c.id = :categoryId')
->setParameter('categoryId', $firstCategoryId)
->getQuery()
->setMaxResults(4)
->getResult();
这总是返回给我前 4 个产品。 假设 ID 为 50 的类别有 100 多种产品。我想要的是从 ID 为 50 的类别中随机查询 4 篇文章。但是如何?这可能吗?当然,我可以不设置 Max Result 而不是使用 PHP 来设置...但是由于性能问题,这不是一个好的解决方案。
【问题讨论】:
-
如果不是很在意速度,可以尝试获取所有产品,打乱结果数组,然后获取前4个元素。
-
看here,这已经回答了
标签: php mysql symfony doctrine-orm