Created
July 30, 2012 14:02
-
-
Save fprochazka/3207083 to your computer and use it in GitHub Desktop.
Get random table row with doctrine DQL in Symfony2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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