是否可以在仍然通过关系访问的同时使用单独的ID数组订购关系集合?
设置Checklist
有很多ChecklistItems
,我以正常方式访问此关系:
foreach ($list->items as $item) {
// More Code Here
}
现在,所需的$item
存在顺序作为属性在$list
属性下的存在$list->item_order
,它只是$item
按用户所需的顺序排列的ID数组,特定于$list
要迭代的ID 。
是否存在一种可行的方法来根据模型所具有的数组对$items
附件进行排序?$list
item_order
$list
(我不能只在'item'表中添加'order'列,b / c订单会根据特定的'list'关系进行更改)。
谢谢你的帮助!
你可以这样做:
$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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句