-
Notifications
You must be signed in to change notification settings - Fork 11.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[5.2] Add random() function to query builder #13642
Conversation
This function adds sql statements to query to get a number of random records.
Does this work with all drivers? |
Unfortunately no. |
Implemented in Grammars. |
Thanks, but sqlite is still missing. |
I've tested this for sqlite and |
Ah, ok, Great. |
In my opinion, this method should NOT do both order by rand AND also limit. As it is possible to seed the RAND() MySQL function, i would expect this method to look like this... public function random($seed = '')
{
return $this->orderByRaw('RAND('.$seed.')');
} if this was the case, i would suggest the method be named ...or at an absolute push, it could be like this... public function random($limit = 1, $seed = '')
{
return $this->orderByRaw('RAND('.$seed.')')->limit($limit);
} Not sure how this translates to other drivers though |
Thanks @JayBizzle, I will do some further research on it. |
Well, I split this function into two functions: This Allows one to use: |
Why not just use $collection->shuffle()? |
That's not helpful if you have many items, but only want to load a few (so combined with a limit) |
Yeh, that won't be possible if there's millions of rows. |
But it’s more feasible to return millions of rows via Eloquent?
|
The use-case is not to get ALL millions rows, but just X random rows from those million. With shuffle(), you would load all rows, but with random SQL, you only get the X rows (although random supposedly isn't very efficient either in MySQL either, but assume better then loading all rows in a collection) |
But why would you get all million? Just use a where clause and LIMIT then call shuffle? $query->where(‘foo’, ‘bar’)->limit(50)->get()->shuffle()?
|
Because you would always get the same 50 results, never the next 50. Simple example; you have a database with jokes (say 1000), and on the frontpage, you want to show a random one. So: |
Gotcha
|
But the |
You don't have to add two methods. You can do:
Also this emphasizes all the rows are ordered before being truncated. This may be a performance issue on large databases. |
Changed this to just a single method: App\User::inRandomOrder()->take(10)->get(); |
Isn't |
Agree with @barryvdh Also reads better IMO |
If someone asked me "how should I sort X?" I would respond with "in random order". |
To me, |
Yes, orderByRandom() is bit clear |
I’m not changing it. Sorry. :/
|
orderByRandom would be better |
Sorry locking this because I'm not going to be spammed all day on my inbox. |
This function adds sql statements to query to get a number of random
records.