Doctrine 2 Randomly Selecting a row (offset 0 or 1 indexed)?

So far, I think that the doctrine has no way of choosing a random string. So I think I have a query to get the number of rows

// pseudo code
$count = SELECT COUNT(i) FROM Item i WHERE ...

Then you have a real request to get the element using a random offset from PHP placed in setFirstResult

$item = (SELECT i FROM Item WHERE ...)->setMaxResults(1)->setFirstResult(rand(0, $count))->getSingleResult()

Question: rand()Do I start with 0 or 1? Then the end? $countor $count-1?

+5
source share
3 answers

setFirstResult() based on 0.

Following your approach, you should use:

->setFirstResult(rand(0, $count - 1))->setMaxResults(1)->getSingleResult();

Source:

I agree that the documentation is unclear on this. However, we see that Doctrine \ DBAL \ Query \ QueryBuilder uses it like this:

->modifyLimitQuery($query, $this->maxResults, $this->firstResult);

SQL Doctrine\DBAL\Platforms\AbstractPlatform:

final public function modifyLimitQuery($query, $limit, $offset = null)
{
    ...
    $query .= ' OFFSET ' . $offset;

OFFSET, 0 SQL, , setFirstResult() 0.

+5

:

$item = (SELECT i FROM Item WHERE ...)
    ->setMaxResults($count)
    ->setFirstResult(1)->getSingleResult();

1

0

Regardless of whether you start from 0 or 1, you must take the appropriate end for counting and counting-1 respectively

0
source

All Articles