Last active
December 31, 2020 03:33
-
-
Save imluxin/5858665 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(); | |
} | |
} |
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/
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
What happens when you start deleting rows in your table? Couldn't that lead to random errors?