加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – 通过ID数组排序Laravel Collection

发布时间:2020-12-14 19:45:21 所属栏目:大数据 来源:网络整理
导读:是否可以使用单独的ID数组来订购关系集合,同时仍然通过关系访问? 设置是Checklist有很多ChecklistItems,我以正常的方式访问这个关系: foreach ($list-items as $item) { // More Code Here} 现在$item的所需顺序作为属性$list- item_order下的$list存在,它
是否可以使用单独的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 IlluminateDatabaseEloquentCollection {

    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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读