laravel 在 Eloquent 中按自定义顺序对集合进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40731863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort collection by custom order in Eloquent
提问by InvalidSyntax
I have an array of ID's as follows:
我有一组 ID,如下所示:
$ids = [5,6,0,1]
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?
使用 Eloquent,我可以使用该->whereIn('id', $ids)
函数搜索这些 Id 。正如预期的那样,这将按 Id 以升序返回结果,有没有办法可以按数组所在的顺序返回结果?或者,按$ids
数组顺序转换集合的最简单方法是什么?
回答by Stephen Lake
If there's a specific order you'd like the records in, you'd have to use the Collection Methods:
如果您希望记录按特定顺序排列,则必须使用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:
要按照您指定的特定顺序获取您的 ID,您可以使用以下sortBy
方法,其中 collection 是您的模型集合:
$ids = [ 5, 6, 0, 1];
$sorted = $collection->sortBy(function($model) use ($ids) {
return array_search($model->getKey(), $ids);
});
// [ 5, 6, 0, 1] // (desired order)
To randomize your collection you can make use of the shuffle
method.
要随机化您的集合,您可以使用该shuffle
方法。
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (generated randomly)
See the Laravel Docson shuffle
and/or sortBy
for more specific requirements.
见Laravel文档上shuffle
和/或sortBy
更具体的要求。
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()'))
.
如果您没有真正考虑特定的顺序,则可以->inRandomOrder()
在 5.2 及更高版本中使用,旧版本将需要使用->orderBy(DB::raw('RAND()'))
.
回答by Luka Peharda
See answer to MySQL order by field in Eloquent. It is possible to order the data in your SQL query. Other answers here are suggesting you sort the data after you've already fetched it in "wrong" order.
请参阅 Eloquent 中对MySQL order by field 的回答。可以对 SQL 查询中的数据进行排序。此处的其他答案建议您在以“错误”顺序获取数据后对数据进行排序。
Your code should look like this:
您的代码应如下所示:
$ids = [5,6,0,1];
$collection = YourModel::whereIn('id', $ids)
->orderByRaw('FIELD (id, ' . implode(', ', $ids) . ') ASC')
->get();
回答by Tim Sheehan
You can pass a function into the sortBy method to perform complex sorting:
您可以将一个函数传递给 sortBy 方法来执行复杂的排序:
$ids = [5,6,0,1];
$collection = YourModel::whereIn('id', $ids)->sortBy(function($model) use ($ids) {
// Access your array order here and modify the sorting here
});