【发布时间】:2017-04-05 12:55:09
【问题描述】:
我有一个 ID 数组,如下所示:
$ids = [5,6,0,1]
使用 Eloquent,我可以使用 ->whereIn('id', $ids) 函数搜索这些 Id。正如预期的那样,这将按 Id 升序返回结果,有没有办法可以按数组所在的顺序返回结果?或者,按照$ids 数组的顺序转换集合的最简单方法是什么?
【问题讨论】:
标签: php arrays laravel eloquent
我有一个 ID 数组,如下所示:
$ids = [5,6,0,1]
使用 Eloquent,我可以使用 ->whereIn('id', $ids) 函数搜索这些 Id。正如预期的那样,这将按 Id 升序返回结果,有没有办法可以按数组所在的顺序返回结果?或者,按照$ids 数组的顺序转换集合的最简单方法是什么?
【问题讨论】:
标签: php arrays laravel eloquent
如果您希望记录按特定顺序排列,则必须使用Collection Methods:
要按照您指定的特定顺序获取您的 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)
要随机化您的收藏,您可以使用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()')) 的原始查询。
【讨论】:
请参阅MySQL order by field in Eloquent 的回复。可以对 SQL 查询中的数据进行排序。此处的其他答案建议您在以“错误”顺序获取数据后对数据进行排序。
您的代码应如下所示:
$ids = [5,6,0,1];
$collection = YourModel::whereIn('id', $ids)
->orderByRaw('FIELD (id, ' . implode(', ', $ids) . ') ASC')
->get();
【讨论】:
$ids 是用户提供的未正确转义的数据,这可能会使您面临 SQL 注入攻击。
您可以将函数传递给 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
});
【讨论】: