Skip to content

Instantly share code, notes, and snippets.

@treetop1500
Created March 21, 2018 18:34
Show Gist options
  • Save treetop1500/a169ec70cdc2d6a9a28780f51188c75e to your computer and use it in GitHub Desktop.
Save treetop1500/a169ec70cdc2d6a9a28780f51188c75e to your computer and use it in GitHub Desktop.
Doctrine Fetch Any Number of Random Results
{
...
"require": {
"luxifer/doctrine-functions": "~1.4",
}
}
doctrine:
...
orm:
...
dql:
...
numeric_functions:
RAND: Luxifer\DQL\Numeric\Rand
<?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();
}
}
<?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