在Eloquent中按自定义顺序对集合进行排序 [英] Sort collection by custom order in Eloquent

查看:144
本文介绍了在Eloquent中按自定义顺序对集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ID数组,如下所示:

I have an array of ID's as follows:

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

使用雄辩,我可以使用->whereIn('id', $ids)函数搜索这些ID.如预期的那样,将按ID升序返回结果,是否有办法按数组所在的顺序返回结果?或者,按$ids数组的顺序转换集合的最简单方法是什么?

Using Eloquent I am able to search for these Id's using the ->whereIn('id', $ids) function. This as expected will return the results in the ascending order by Id, is there a way I can return the results on the order the array is in? alternatively whats the easiest way to convert the collection in the order of the $ids array?

推荐答案

如果有特定的顺序需要记录,则必须使用

If there's a specific order you'd like the records in, you'd have to use the Collection Methods:

要按照指定的特定顺序获取ID,可以按以下方式使用sortBy方法,其中collection是模型的集合:

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)

要随机化集合,可以使用shuffle方法.

To randomize your collection you can make use of the shuffle method.

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

$shuffled = $collection->shuffle();

$shuffled->all();

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

请参见shuffle和/或sortBy上的 Laravel文档.了解更多具体要求.

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

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

If you don't really have a specific order in mind, you can use ->inRandomOrder() in version 5.2 and up, older versions would require the raw query using ->orderBy(DB::raw('RAND()')).

这篇关于在Eloquent中按自定义顺序对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆