I'm new to Doctrine and had a hard time deciding how to get random rows within it without creating custom DQL functions or using a native query. The solution I have come up with is below, this is within a custom repository for an Entity. I'm hoping for some constructive criticism in regards to it, however it currently is working. 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);}}
Selecting random results within Doctrine
php;doctrine