Skip to content

Instantly share code, notes, and snippets.

@imluxin
Last active December 31, 2020 03:33
Show Gist options
  • Select an option

  • Save imluxin/5858665 to your computer and use it in GitHub Desktop.

Select an option

Save imluxin/5858665 to your computer and use it in GitHub Desktop.
Get random table row with doctrine DQL in Symfony2
<?php
//
// Theory (for MySQL): http://jan.kneschke.de/projects/mysql/order-by-rand/
//
class QuestionRepository extends EntityRepository
{
public function findOneRandom()
{
$em = $this->getEntityManager();
$max = $em->createQuery('
SELECT MAX(q.id) FROM EnzimQuestionBundle:Question q
')
->getSingleScalarResult();
return $em->createQuery('
SELECT q FROM EnzimQuestionBundle:Question q
WHERE q.id >= :rand
ORDER BY q.id ASC
')
->setParameter('rand',rand(0,$max))
->setMaxResults(1)
->getSingleResult();
}
}
@danielroehrig

Copy link
Copy Markdown

What happens when you start deleting rows in your table? Couldn't that lead to random errors?

@niketpathak

Copy link
Copy Markdown

lol. true. you can use native SQL in doctrine or write a custom numeric function to avoid those random errors. http://digitalfortress.tech/php/get-random-rows-in-doctrine/

@eissasoubhi

Copy link
Copy Markdown

Replacing MAX with COUNT resolves the random errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment