php - 如何使用 eloquent 模型获取随机记录

标签 php laravel

这个问题在这里已经有了答案:





Laravel - Eloquent or Fluent random row

(17 个回答)


2年前关闭。




我试图从 Laravel 5.7 中的表中获取随机数的行,但我找不到任何解决方案。
我用过

 Model::all()->random(2);

它工作正常。但我需要像 Model::select('column')->where('column','value')->random(number of rows'); 一样应用 where 子句
那么我如何使用 eloquent 来实现这一点。
请给我任何建议。

最佳答案

您可以简单地添加到链 inRandomOrder ,正如这里所建议的:

Laravel - Eloquent or Fluent random row

然后限制你的数据集。

Model::select('column')
    ->where('column','value')
    ->inRandomOrder()
    ->limit(2) // here is yours limit
    ->get();

关于php - 如何使用 eloquent 模型获取随机记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54999726/

相关文章:

PHP,检查电子邮件是否已在数据库中

php - SED 命令 : won't insert the string I want

laravel - 使用Eloquent仅获取联接表上的最新值

php - Laravel - 如何访问自定义类中的 App 对象?

php - 在 laravel 项目 Stripe\Exception\ApiConnectionException 上连接 strip api 时出错

php - Mysql Views - 自动增量不工作(通过 Eloquent ORM)

user-interface - 使用 PHP CLI 创建 GUI

php - Codeigniter 重定向不使用 jQuery Mobile 更新 url

php - symfony fosuserbundle 自定义登录

php - 获取关注者的帖子 laravel