Laravel展平并从多维集合中拔出

问题描述 投票:2回答:2

我必须从给定的集合中仅检索id的数组,类似于[10,54,61,21,etc]。我已经尝试过flattenpluck,但是除了foreach似乎没有其他工作,我想在此步骤中将其删除。

// Model
class Children extends Eloquent {
    public function directChildrens(){
        return $this->hasMany('App\Children','father_id','id')->select('id','father_id');
    }

    public function childrens(){
        return $this->directChildrens()->with('childrens');
    }
}

// Controller
return $children->childrens()->get();

如预期般运作良好。结果如下:

[{
"id": 10,
"father_id": 2,
"childrens": [
    {
        "id": 54,
        "father_id": 10,
        "childrens": [
            {
                "id": 61,
                "father_id": 54,
                "childrens": []
            }
        ]
    },
    {
        "id": 21,
        "father_id": 10,
        "childrens": []
    }
]
}]

如何执行此集合的pluck('id')以获取[10,54,61,21]吗?

arrays laravel eloquent hierarchy
2个回答
0
投票
$result = [
            [
                "id" => 10,
                "father_id" => 2,
                "childrens" => [
                    [
                        "id" => 54,
                        "father_id" => 10,
                        "childrens" => [
                            [
                                "id" => 61,
                                "father_id" => 54,
                                "childrens" => []
                            ]
                        ]
                    ],
                    [
                        "id" => 21,
                        "father_id" => 10,
                        "childrens" => []
                    ]
                ]
            ]
        ];
return collect($result)
        ->map(function ($value) {
            return array_dot($value); // converts it to the dot notation version
        })
        ->collapse() // collapsing them into a single one
        ->filter(function ($value, $key) {
            return $key === 'id' || Str::endsWith($key, '.id'); // getting first id + patterns
        })
        ->values() // discard dot notation keys
        ->toArray();

array_dot helper将集合转换为以下格式,从而使所有内容都处于同一级别。

[
  {
    "id": 10,
    "father_id": 2,
    "childrens.0.id": 54,
    "childrens.0.father_id": 10,
    "childrens.0.childrens.0.id": 61,
    "childrens.0.childrens.0.father_id": 54,
    "childrens.0.childrens.0.childrens": [],
    "childrens.1.id": 21,
    "childrens.1.father_id": 10,
    "childrens.1.childrens": []
  }
]

-1
投票

这里是一种递归算法,您可以将其添加到Children模型中:

use Illuminate\Support\Collection;

public function getAllChildrenIds()
{
    return Collection::make([$this->getKey()])
        ->merge(
            $this->childrens->map->getAllChildrenIds()
        );
}
© www.soinside.com 2019 - 2024. All rights reserved.