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带S3存储器

Laravel Debugbar 中的 Laravel api routes路由

处理程序类中的错误 - Laravel

laravel render() 方法有什么用?

Laravel - 如果值包含某个字符串(取自搜索输入),则查询模型

FileViewFinder.php 第 137 行中的 Laravel 5 InvalidArgumentException:未找到视图 [.admin]

为什么 laravel 模型会重复一组数据以及如何(如果可能)只有一组数据?

使用 Amazon S3 的 Storage::get() 返回 false

Laravel Blade:@stop VS @show VS @endsection VS @append

调用未定义函数 Illuminate\Encryption\openssl_decrypt()

SQLSTATE [HY000]:一般错误:1005 无法创建表 - Laravel 4

laravel Blade中多选选项中的旧值

Laravel 控制器构造

Laravel 分页方法不适用于 map 集合?

Laravel - DecryptException:'MAC 无效'

Laravel 5 - 判断日期是否是今天

Laravel 5 事件处理程序未触发

日期时间格式无效:1366 字符串值不正确

如何在 laravel eloquent 中保存布尔值

Laravel 4 控制器模板/Blade - 正确的方法?