問題描述
我有一組 ID,如下所示:
I have an array of ID's as follows:
$ids = [5,6,0,1]
使用 Eloquent,我可以使用 ->whereIn('id', $ids)
函數(shù)搜索這些 Id.正如預(yù)期的那樣,這將按 Id 以升序返回結(jié)果,有沒有辦法可以按數(shù)組所在的順序返回結(jié)果?或者,按 $ids
數(shù)組的順序轉(zhuǎn)換集合的最簡單方法是什么?
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?
推薦答案
如果您希望記錄按特定順序排列,則必須使用 收集方法:
If there's a specific order you'd like the records in, you'd have to use the Collection Methods:
要按照您指定的特定順序獲取 ID,您可以使用 sortBy
方法,如下所示,其中 collection 是您的模型集合:
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)
要隨機化您的集合,您可以使用 shuffle
方法.
To randomize your collection you can make use of the shuffle
method.
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (generated randomly)
請參閱 shuffle
上的 Laravel 文檔 和/或 sortBy
以獲得更具體的要求.
See the Laravel Docs on shuffle
and/or sortBy
for more specific requirements.
如果您沒有真正考慮特定的順序,您可以在 5.2 及更高版本中使用 ->inRandomOrder()
,舊版本將需要使用 - 的原始查詢>orderBy(DB::raw('RAND()'))
.
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()'))
.
這篇關(guān)于在 Eloquent 中按自定義順序?qū)线M行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!