使用Doctrine获取随机结果

时间:2015-09-16 22:44:48

标签: php symfony doctrine-orm doctrine

我是Doctrine的新手,很难在不创建自定义DQL函数或使用本机查询的情况下决定如何在其中获取随机行。 我提出的解决方案如下,这是一个实体的自定义存储库。我希望对它有一些建设性的批评,但它目前正在发挥作用。

class MyRepository extends EntityRepository
{

/**
 * @param int $numberOfResults
 * @return array
 */
public function getRandomResults($numberOfResults = 1)
{
    $maxID = $this->getMax();
    $count = 0;
    $randomNumberCounter = 0;
    $randomNumbers = array();
    while ($randomNumberCounter < $numberOfResults) {
        $randomNumberCounter++;
        $randomNumbers[] = $this->getRandom(0, $maxID);
    }

    $qb = $this->createQueryBuilder('r');
    while ($count < $numberOfResults) {
        $qb
            ->andWhere(
                $qb->expr()->orX(
                    // the greater than is to account for holes within the primary key
                    $qb->expr()->gte("r.id", "?".$count),
                    /* the less than is in case we have a beginning database with a large disparity
                    between starting and ending ID */
                    $qb->expr()->lte("r.id", "?".$count)
                )
            );
        $count++;
    }
    $result = $qb
        ->setParameters($randomNumbers)
        ->setMaxResults($numberOfResults)
        // ensure we have no duplicates
        ->groupBy('r.id')
        ->getQuery();

    return $result->getResult();
}


/**
 * get the maximum ID that the table has
 * @return mixed
 * TODO: Create a Cron job to set this every 6 hours
 */
public function getMax()
{
    $maxID = $this->createQueryBuilder('r')
        ->select('(MAX(r.id))')
        ->getQuery()
        ->getSingleScalarResult();
    return $maxID;
}

/**
 * @param $min
 * @param $max
 * @return int
 */
public function getRandom($min, $max)
{
    return mt_rand($min, $max);
}
}

0 个答案:

没有答案