我有以下数据库方案:
table 'products'
id
category_id
当然还有一个类别表,只有一个id。
数据看起来像这样:
Products
--------------------
| id | category_id |
--------------------
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | 1 |
--------------------
我想选择一个类别(例如类别1),所以我在我的产品存储库类中选择该类别中的所有行:
return $this
->createQueryBuilder('u')
->andWhere('u.category = :category')
->setMaxResults(1)
->setParameter('category', $category->getId())
->getQuery()
->getSingleResult()
;
我现在如何选择一个随机产品?还有:有可能通过人际关系来解决这个问题吗?
我在实体"Category"answers"Product"之间有一个OneToMany关系,所以我也可以通过Category ->getProducts()…
任何帮助将是非常有用的,谢谢
您首先必须计算产品总数,然后生成随机偏移量以选择随机产品。
这应该让你开始:
$count = $this->createQueryBuilder('u')
->select('COUNT(u)')
->getQuery()
->getSingleScalarResult();
然后你可以在你的1和总行数之间生成一个随机数
return $this->createQueryBuilder('u')
->where('u.category = :category')
->setFirstResult(rand(0, $count - 1))
->setMaxResults(1)
->setParameter('category', $category->getId())
->getQuery()
->getSingleResult()
;
翻译过来就是:
SELECT * FROM products WHERE category_id = ? LIMIT 1, {random offset}
使用这个辅助函数:
<?php
use Doctrine'ORM'EntityManager;
/**
* Retrieve one random item of given class from ORM repository.
*
* @param EntityManager $em The Entity Manager instance to use
* @param string $class The class name to retrieve items from
* @return object
*/
function getRandomDoctrineItem(EntityManager $em, $class)
{
static $counters = [];
if (!isset($counters[$class])) {
$this->counters[$class] = (int) $this->manager->createQuery(
'SELECT COUNT(c) FROM '. $class .' c'
)->getSingleScalarResult();
}
return $em
->createQuery('SELECT c FROM ' . $class .' c ORDER BY c.id ASC')
->setMaxResults(1)
->setFirstResult(mt_rand(0, $counters[$class] - 1))
->getSingleResult()
;
}
使用例子:
$randomItem = getRandomDoctrineItem($em, 'Application'Entity'Post');