Selecting Random Rows in Laravel Using Eloquent and Fluent
When working with large datasets, it is often necessary to retrieve random rows from the database without having to perform a preparatory count. Laravel provides several options for achieving this using both Eloquent and Fluent interfaces.
Eloquent
Laravel 5.2 and above offers the inRandomOrder() method:
User::inRandomOrder()->get();
This method returns a collection of all random rows from the specified model. To limit the number of rows retrieved, use the limit() method:
User::inRandomOrder()->limit(5)->get();
To retrieve a single random row, use the first() method:
User::inRandomOrder()->first();
For older versions of Laravel (4.2.7 - 5.1), you can use the orderByRaw() method:
User::orderByRaw("RAND()")->get();
For Laravel versions 4.0 - 4.2.6, use:
User::orderBy(DB::raw('RAND()'))->get();
Fluent
In versions of Laravel prior to 5.2, the order_by() method was used with the DB::raw() helper function:
User::order_by(DB::raw('RAND()'))->get();
Additional Considerations
It is important to note that the orderBy() method does not currently allow for any arguments other than ASC or DESC. Therefore, it is necessary to use the orderByRaw() method or inRandomOrder() method for selecting random rows.
Performance Considerations
When retrieving large numbers of rows, it is important to consider the impact on performance. Using the inRandomOrder() method may be more efficient than using the orderByRaw() method, as it does not require an additional subquery to generate random ordering.
The above is the detailed content of How to Select Random Rows in Laravel Using Eloquent and Fluent?. For more information, please follow other related articles on the PHP Chinese website!