Reputation: 88217
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
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
Reputation: 344
No matter you start from 0 or 1 , you must take the respective end to count and count-1 respectively
Upvotes: 0
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