Laravel 随机排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40551388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:43:49  来源:igfitidea点击:

Laravel OrderBy Random

laravelsql-order-by

提问by Vfero

As a novice in Laravel, i'm trying to display the images of a gallery randomly. In routes.php, I currently have this code:

作为 Laravel 的新手,我试图随机显示画廊的图像。在routes.php 中,我目前有以下代码:

// Get galleries
$galleries = App\Gallery::orderBy('id', 'DESC')->get();

Do you have any idea to make it work?

你有什么想法让它工作吗?

Thanks

谢谢

回答by Zakaria Acharki

For Laravel >= 5.2 you could use inRandomOrder()method.

对于 Laravel >= 5.2 你可以使用inRandomOrder()method。

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:

说明:inRandomOrder()方法可用于对查询结果进行随机排序。例如,您可以使用此方法来获取随机用户:

Example :

例子 :

$galleries = App\Gallery::inRandomOrder()->get();
//Or
DB::table('gallery')->inRandomOrder()->get();


For other versions >= 5.0 you could use random()method.

对于 >= 5.0 的其他版本,您可以使用random()方法。

Description :The random()method returns a random item from the collection.

描述:random()方法从集合中返回一个随机项目。

Example :

例子 :

App\Gallery::all()->random()->get();

Hope this helps.

希望这可以帮助。

回答by Amit Gupta

You can try as:

您可以尝试如下:

$galleries = App\Gallery::orderByRaw('RAND()')->get()