Last active
May 6, 2016 23:33
-
-
Save ZeeCoder/7f3d51b7f3fa68889739 to your computer and use it in GitHub Desktop.
Doctrine2: Get Random Entity
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 | |
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