Created
March 21, 2018 18:34
-
-
Save treetop1500/a169ec70cdc2d6a9a28780f51188c75e to your computer and use it in GitHub Desktop.
Doctrine Fetch Any Number of Random Results
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
{ | |
... | |
"require": { | |
"luxifer/doctrine-functions": "~1.4", | |
} | |
} |
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
doctrine: | |
... | |
orm: | |
... | |
dql: | |
... | |
numeric_functions: | |
RAND: Luxifer\DQL\Numeric\Rand |
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 | |
namespace AppBundle\Repository; | |
use Doctrine\ORM\EntityRepository; | |
class MyRepository extends EntityRepository | |
{ | |
public function findRandom($numResults) | |
{ | |
$qb = $this->createQueryBuilder('i'); | |
$qb->select('i, RAND() AS HIDDEN r') | |
->setParameter("b", true) | |
->orderBy('r', 'ASC') | |
->setMaxResults($numResults); | |
$query = $qb->getQuery(); | |
return $query->getResult(); | |
} | |
} |
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 | |
namespace GrayLoon\AppBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Symfony\Component\HttpFoundation\Request; | |
class MyController extends Controller | |
{ | |
public function indexAction(Request $request) | |
{ | |
$em = $this->getDoctrine()->getManager(); | |
$work = $em->getRepository('AppBundle:My')->findRandom(4); | |
return $this->render( | |
'::index.html.twig', | |
array( | |
'entities' => $entities, | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment