Laravel 随机排序

标签 laravel sql-order-by

作为 Laravel 的新手,我试图随机显示画廊的图像。在 路线.php ,我目前有这个代码:

// Get galleries
$galleries = App\Gallery::orderBy('id', 'DESC')->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();

希望这可以帮助。

关于Laravel 随机排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40551388/

相关文章:

php - Mysql ORDER BY 使用日期数据行

php - 不允许序列化 'Doctrine\DBAL\Driver\PDOConnection'

laravel - 为什么我的 Redis Docker 容器为 KEYS * 显示 "(empty array)",而我绝对确定它有缓存数据并且工作正常

php - 如何修复VerifyCsrfToken.php第46行: using ajax and laravel 5. 0中的TokenMismatchException?

MySQL行号

sql-server - SQL 服务器 : select distinct by one column and by another column value

mysql - 在 SQL 中从多对多关系创建队列

php - 如何在 Laravel 中将 INFO 记录到单独的文件中

php - Laravel如何配置发件人姓名而不是电子邮件地址

mysql - 按过去一小时的观看次数排序 [MySQL]