I have an array of ID's as follows:
$ids = [5,6,0,1]
使用eloquent,我可以使用->whereIn('id', $ids)
函数搜索这些ID.不出所料,这将按ID以升序返回结果,有没有方法可以按数组的顺序返回结果?或者,按照$ids
数组的顺序转换集合的最简单方法是什么?
I have an array of ID's as follows:
$ids = [5,6,0,1]
使用eloquent,我可以使用->whereIn('id', $ids)
函数搜索这些ID.不出所料,这将按ID以升序返回结果,有没有方法可以按数组的顺序返回结果?或者,按照$ids
数组的顺序转换集合的最简单方法是什么?
如果你想要记录的具体顺序,你必须使用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:
$ids = [ 5, 6, 0, 1];
$sorted = $collection->sortBy(function($model) use ($ids) {
return array_search($model->getKey(), $ids);
});
// [ 5, 6, 0, 1] // (desired order)
要将你的Collection 随机化,你可以使用shuffle
法.
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (generated randomly)
See the Laravel Docs on shuffle
and/or sortBy
for more specific requirements.
如果您实际上没有具体的顺序,可以在5.2及更高版本中使用->inRandomOrder()
,旧版本将需要使用->orderBy(DB::raw('RAND()'))
进行原始查询.