我必须从给定的集合中仅检索id的数组,类似于[10,54,61,21,etc]。我已经尝试过flatten,pluck,但是除了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]吗?
$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": []
}
]
这里是一种递归算法,您可以将其添加到Children
模型中:
use Illuminate\Support\Collection;
public function getAllChildrenIds()
{
return Collection::make([$this->getKey()])
->merge(
$this->childrens->map->getAllChildrenIds()
);
}