I have an array of ID's as follows:

$ids = [5,6,0,1]

使用eloquent,我可以使用->whereIn('id', $ids)函数搜索这些ID.不出所料,这将按ID以升序返回结果,有没有方法可以按数组的顺序返回结果?或者,按照$ids数组的顺序转换集合的最简单方法是什么?

推荐答案

如果你想要记录的具体顺序,你必须使用Collection Methods:

To get your ID's in the very specific order you've specified, you can make use of the sortBy method as follows, where collection is your collection of models:

$ids = [ 5, 6, 0, 1];

$sorted = $collection->sortBy(function($model) use ($ids) {
    return array_search($model->getKey(), $ids);
});

// [ 5, 6, 0, 1] // (desired order)

要将你的Collection 随机化,你可以使用shuffle法.

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] // (generated randomly)

See the Laravel Docs on shuffle and/or sortBy for more specific requirements.

如果您实际上没有具体的顺序,可以在5.2及更高版本中使用->inRandomOrder(),旧版本将需要使用->orderBy(DB::raw('RAND()'))进行原始查询.

Laravel相关问答推荐

Laravel使用PostgreSQL显示";`try 读取null`上的属性,而不是SQL错误消息

如何定制有关密码被泄露的Laravel Breeze S消息?

为什么我的 Laravel 开发服务器不提供 public 文件夹下的文件?

导出所有客户端不起作用,文件保存时没有名称和扩展名

无法在 Laravel 项目中安装 @vitejs/plugin-vue

Laravel Livewire 组件在刷新后不会自动刷新/重新加载

Laravel 从 5.1 升级到 5.2.0 错误

如何在laravel中将数组转换为字符串?

Laravel 不验证是否不需要字段

错误try 访问 null 类型值的数组偏移量laravel 5.8.26 Php 7.4.2

在 laravel 5 中的表单请求验证后传递旧输入

Laravel 5.1 如何在Blade 文件上使用 {{ old('') }} 助手进行无线电输入

Laravel 5.x 中 onUpdate / onDelete 的可用操作

在 Laravel Blade 中转义 vue.js 数据绑定语法?

Laravel excel maatwebsite 3.1 导入,excel 单元格中的日期列返回为未知格式数字.如何解决这个问题?

Composer RuntimeException - 无法加载软件包 mews/purifier

配置和测试 Laravel 任务调度

在 vue.js 中使用 Laravel 的Gate/Authorization

Laravel 仓库

Laravel s3 多桶