我有一个ID数组,如下所示:
$ids = [5,6,0,1]
使用 Eloquent,我可以使用 ->whereIn('id', $ids)
函数来搜索这些 Id。预期的结果是按照 Id 升序返回结果,有没有一种方法可以按照数组中的顺序返回结果?或者,最简单的方法是将集合按照 $ids
数组的顺序进行转换?要按您指定的非常特定的顺序获取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)
查看Laravel文档中有关shuffle
和/或sortBy
的更具体要求。
如果您没有特定的排序顺序,请使用版本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 = [5,6,0,1];
$collection = YourModel::whereIn('id', $ids)->sortBy(function($model) use ($ids) {
// Access your array order here and modify the sorting here
});
$ids
是未经适当转义的用户提供数据,则可能会导致 SQL 注入攻击。 - Wireblue