1

I have entity Travel, let's say it has 30 entries for example :

1-
2- 
3-
4-
.
.
.
30-

I'd like to select 6 entity randomly, for example : 2, 14, 7, 25, 16, 1

I have tried this code but it works, but the results are always displayed by order ASC (3,4,5,6,7,8,).

    public function getRandomTravelsFrontend()
    {
    $count = $this->createQueryBuilder('t')
         ->select('COUNT(t)')
         ->getQuery()
         ->getSingleScalarResult();

$qb = $this->createQueryBuilder('t')
        ->leftJoin('t.image', 'i')
        ->addSelect('i')
        ->Where('t.enabled = 1')
        ->setMaxResults(6)
        ->setFirstResult(rand(0, $count - 6));

        return $qb->getQuery()->getResult();
  }

How to display result by random order ? and is it possible to select 6 entities like this : 2, 14, 7, 25, 16, 1 ?

hous
  • 2,577
  • 2
  • 27
  • 66
  • How many rows does that query return in total (if you don't `LIMIT` it)? – zerkms Jan 06 '15 at 22:22
  • Use random number generator to order the rows, see: http://stackoverflow.com/questions/23112845/using-rand-function-from-sql-with-doctrine2 – ptrk Jan 06 '15 at 22:25
  • @zerkms , you mean if I remove `->setMaxResults(6)` or what ? if I remove it , the number of rows changed every time, sometimes 2 rows, sometimes 7 rows... – hous Jan 06 '15 at 22:42

1 Answers1

-3

You can use ORDER BY rand() in your SQL select statement.

Bee00LA
  • 30
  • 3