Search code examples
doctrine-ormdql

Doctrine 2 Randomly Selecting a Row (Offset 0 or 1 indexed)?


So far, I think doctrine doesn't have a way of selecting a random row. So I am thinking I have a query to get the count of rows

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

Then have a real query to get the item using a random offset from PHP put into setFirstResult

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

Question is, my rand() do I start from 0 or 1? Then the end? $count or $count-1?


Solution

  • setFirstResult() is 0-based.

    Following your approach, you have to use:

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

    Source:

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

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

    Which is then translated to SQL in Doctrine\DBAL\Platforms\AbstractPlatform:

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

    OFFSET being 0-based in SQL, we can deduct that setFirstResult() is 0-based as well.