I have the following database scheme:
table \'products\'
id
category_id
and of course a category table, just with an id.
The data look
Use this helper function:
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');