Reputation: 1811
I have this kind of eloquent query where I need to take random rows from a table, with a limit, but it returns wrong, when I use limit, then it pulls only one row, no matter what number I take in as a limit. And when I don't use limit it returns random number of rows. Don't know what I am missing. This is the code.
$questions = $query->whereRaw('RAND()')->take($limit)->get();
Thanks in advance!
Upvotes: 0
Views: 308
Reputation: 16373
You should have been using orderByRaw
.
But there is a better solution, you can add this macro:
use Illuminate\Database\Query\Builder;
Builder::macro('orderByRandom', function () {
$randomFunctions = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
$driver = $this->getConnection()->getDriverName();
return $this->orderByRaw($randomFunctions[$driver]);
});
So you can do: $query->orderByRandom()->take($limit)->get();
Upvotes: 5
Reputation: 1709
You are using RAND in your where, it shout be in the ORDER BY
$questions = $query->orderByRaw('RAND()')->take($limit)->get();
Upvotes: 0