Jiew Meng
Jiew Meng

Reputation: 88217

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?

Upvotes: 6

Views: 3218

Answers (3)

BenMorel
BenMorel

Reputation: 36524

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.

Upvotes: 6

Bharath Gupta
Bharath Gupta

Reputation: 344

No matter you start from 0 or 1 , you must take the respective end to count and count-1 respectively

Upvotes: 0

rkmax
rkmax

Reputation: 18133

I use in my app:

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

start to count from 1 until the total of records

Upvotes: 0

Related Questions