Skip to content

Instantly share code, notes, and snippets.

@ZeeCoder
Last active May 6, 2016 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZeeCoder/7f3d51b7f3fa68889739 to your computer and use it in GitHub Desktop.
Save ZeeCoder/7f3d51b7f3fa68889739 to your computer and use it in GitHub Desktop.
Doctrine2: Get Random Entity
<?php
public function getRandomNewsArticles($n, $ignoredId = null) {
$idArray =
$this->em
->createQueryBuilder('na')
->select('na.id')
->add('from', '\App\Entity\NewsArticle na')
->getQuery()
->getScalarResult();
$randomKeys = array_rand($idArray, $n);
$randomKeys = array_map(function($key) use ($idArray) {
return $idArray[$key]['id'];
}, $randomKeys);
if ($ignoredId !== null) {
unset($randomKeys[array_search($ignoredId, $randomKeys)]);
}
return
$this->em
->createQueryBuilder('na')
->select('na')
->add('from', '\App\Entity\NewsArticle na')
->andWhere('na.id IN (:random_keys)')
->setParameter('random_keys', $randomKeys) //, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY
->getQuery()
->getResult();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment