客户订单我有ID的数组如下:排序集合在雄辩
$ids = [5,6,0,1]
用雄辩的我能够搜索这些标识的使用->whereIn('id', $ids)
功能。如预期的那样,将按照Id的升序返回结果,有没有方法可以按照数组的顺序返回结果?或者按照$ids
阵列的顺序转换集合最简单的方法是什么?
客户订单我有ID的数组如下:排序集合在雄辩
$ids = [5,6,0,1]
用雄辩的我能够搜索这些标识的使用->whereIn('id', $ids)
功能。如预期的那样,将按照Id的升序返回结果,有没有方法可以按照数组的顺序返回结果?或者按照$ids
阵列的顺序转换集合最简单的方法是什么?
如果有一个特定的顺序,你想,你就必须记录使用Collection Methods:
为了让您的ID在您所指定的非常具体的命令,你可以使用sortBy
方法如下,其中收集您的收藏模式:
$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
方法。
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (generated randomly)
查看shuffle
和/或sortBy
的Laravel Docs了更具体的要求。
如果您确实没有特定的顺序,则可以在版本5.2及更高版本中使用->inRandomOrder()
,旧版本需要使用->orderBy(DB::raw('RAND()'))
的原始查询。
你可以传递函数为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
});
你错过了“)”在你上面的$排序代码片段。 –
修复了缺少支架错字,谢谢。 – snh