Skip to content

Instantly share code, notes, and snippets.

@fprochazka
Created July 30, 2012 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fprochazka/3207083 to your computer and use it in GitHub Desktop.
Save fprochazka/3207083 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment