5

我有以下数据库方案:

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”和“Product”之间有一个 OneToMany 关系,所以我也可以通过 category->getProducts()...

任何帮助都会非常有用,谢谢

4

2 回答 2

12

您首先必须计算产品总数,然后生成随机偏移量以选择随机产品。

这应该让你开始:

$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}
于 2013-05-18T20:59:53.597 回答
-1

使用这个辅助函数:

<?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');
于 2017-03-03T21:58:12.567 回答