我有一组 ID,如下所示:
I have an array of ID's as follows:
$ids = [5,6,0,1]
使用 Eloquent,我可以使用 ->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
上的 Laravel 文档 和/或 sortBy
以获得更具体的要求.
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 中按自定义顺序对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!