Skip to content

Instantly share code, notes, and snippets.

@mingomax
Forked from imluxin/gist:5858665
Created October 11, 2016 22:49
Show Gist options
  • Save mingomax/aa464163dc6c87065a421eb3bf60dd4c to your computer and use it in GitHub Desktop.
Save mingomax/aa464163dc6c87065a421eb3bf60dd4c 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