是否可以使用单独的ID数组来订购关系集合,同时仍然通过关系访问?
设置是Checklist有很多ChecklistItems,我以正常的方式访问这个关系:
foreach ($list->items as $item) { // More Code Here }
现在$item的所需顺序作为属性$list-> item_order下的$list存在,它只是用户所需顺序中的$item ID数组,特定于迭代的$list.
是否有一种可行的方法来根据$list模型具有的item_order数组来订购附加到$list的$items?
(我不能只在’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); }