你可以这样做:
$order = $list->item_order;
$list->items->sortBy(function($model) use ($order){
return array_search($model->getKey(),$order);
}
您还可以向模型添加属性访问器,它也会执行相同操作
public function getSortedItemsAttribute()
{
if ( ! is_null($this->item_order)) {
$order = $this->item_order;
$list = $this->items->sortBy(function($model) use ($order){
return array_search($model->getKey(),$order);
});
return $list;
}
return $this->items;
}
foreach ($list->sortedItems as $item) {
// More Code Here
}
如果您需要在多个地方使用此类功能,我建议您创建自己的Collection类:
class MyCollection extends Illuminate\Database\Eloquent\Collection {
public function sortByIds(array $ids){
return $this->sortBy(function($model) use ($ids){
return array_search($model->getKey(),$ids);
}
}
}
然后,实际使用该类重写模型中的newCollection().在这种情况下,它将在ChecklistItems类中:
public function newCollection(array $models = array())
{
return new MyCollection($models);
}