Laravel 随机排序
Laravel OrderBy Random
作为 Laravel 的新手,我正在尝试随机显示画廊的图像。在routes.php中,我目前有这个代码:
// Get galleries
$galleries = App\Gallery::orderBy('id', 'DESC')->get();
你有什么想法让它发挥作用吗?
谢谢
您可以试试:
$galleries = App\Gallery::orderByRaw('RAND()')->get()
对于 Laravel >= 5.2 你可以使用 inRandomOrder()
方法。
Description : The inRandomOrder()
method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:
示例:
$galleries = App\Gallery::inRandomOrder()->get();
//Or
DB::table('gallery')->inRandomOrder()->get();
对于其他版本 >= 5.0 你可以使用 random()
方法。
Description : The random()
method returns a random item from the collection.
示例:
App\Gallery::all()->random()->get();
希望对您有所帮助。
如果你想对已经检索到的集合进行随机排序,你可以使用类似这样的方法
$result = $result->sortBy(function($item){
return rand();
});
作为 Laravel 的新手,我正在尝试随机显示画廊的图像。在routes.php中,我目前有这个代码:
// Get galleries
$galleries = App\Gallery::orderBy('id', 'DESC')->get();
你有什么想法让它发挥作用吗?
谢谢
您可以试试:
$galleries = App\Gallery::orderByRaw('RAND()')->get()
对于 Laravel >= 5.2 你可以使用 inRandomOrder()
方法。
Description : The
inRandomOrder()
method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:
示例:
$galleries = App\Gallery::inRandomOrder()->get();
//Or
DB::table('gallery')->inRandomOrder()->get();
对于其他版本 >= 5.0 你可以使用 random()
方法。
Description : The
random()
method returns a random item from the collection.
示例:
App\Gallery::all()->random()->get();
希望对您有所帮助。
如果你想对已经检索到的集合进行随机排序,你可以使用类似这样的方法
$result = $result->sortBy(function($item){
return rand();
});