Skip to content

Instantly share code, notes, and snippets.

@Thinkscape
Last active November 25, 2015 11:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Thinkscape/124d658e4076421c0516 to your computer and use it in GitHub Desktop.
Save Thinkscape/124d658e4076421c0516 to your computer and use it in GitHub Desktop.
Get random item from Doctrine2 repository
<?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