Home > Enterprise >  How can I use 'order by rand' in Symfony doctrine?
How can I use 'order by rand' in Symfony doctrine?

Time:06-28

I am trying to use the possibilities of Doctrine in Symfony. How can I do an 'orderBy rand' following this logic:

findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)

Here's what I have so far (but it doesn't work):

$this->entityManager->getRepository(people::class)->findBy([ 'visible' => true ], [ 'name' => 'rand()' ], 8);

I already have the extension 'beberlei/doctrineextensions'

thank you in advance for your help

CodePudding user response:

You cannot use findBy with a custom dql method since it only expect an array with key (property name) and value (ASC or DESC).

So you have to create a custom method in your PeopleRepository to do it.

For example:

function findRandom($isVisible = true)
{
        return $this->createQueryBuilder('p')
            ->andWhere('p.visible = :visible')
            ->setParameter('visible', $isVisible)
            ->orderBy('RAND()')
            ->getQuery()
            ->getResult()
        ;
}
  • Related