-
-
Save sblmasta/190feae074d3775e08f0 to your computer and use it in GitHub Desktop.
Get random item from Doctrine2 repository
This file contains hidden or 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 | |
use Doctrine\ORM\EntityManager; | |
/** | |
* Retrieve one random item of given class from ORM repository. | |
* | |
* @param EntityManager $em The Entity Manager instance to use | |
* @param string $class The class name to retrieve items from | |
* @return object | |
*/ | |
function getRandomDoctrineItem(EntityManager $em, $class) | |
{ | |
static $counters = []; | |
if (!isset($counters[$class])) { | |
$this->counters[$class] = (int) $this->manager->createQuery( | |
'SELECT COUNT(c) FROM '. $class .' c' | |
)->getSingleScalarResult(); | |
} | |
return $em | |
->createQuery('SELECT c FROM ' . $class .' c ORDER BY c.id ASC') | |
->setMaxResults(1) | |
->setFirstResult(mt_rand(0, $counters[$class] - 1)) | |
->getSingleResult() | |
; | |
} | |
// Example usage: | |
$randomItem = getRandomDoctrineItem($em, 'Application\Entity\Post'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment