如何根据类别id获取laravel中的所有子类别id?
我试图递归地从顶级类别到最底层的子类别获取所有子类别ID。我已经为每个类别设置了一个父id,对于最顶端的类别,我使用零作为父类别。我得到了子类别的列表,但不是全部。请帮忙 控制器代码如何根据类别id获取laravel中的所有子类别id?,laravel,Laravel,我试图递归地从顶级类别到最底层的子类别获取所有子类别ID。我已经为每个类别设置了一个父id,对于最顶端的类别,我使用零作为父类别。我得到了子类别的列表,但不是全部。请帮忙 控制器代码 public function index($slug){ $category=Category::where('category_slug',$slug)->first(); if(!empty($category)){ $category_ids=$this->Ge
public function index($slug){
$category=Category::where('category_slug',$slug)->first();
if(!empty($category)){
$category_ids=$this->GetAllChildCategoryIDS($category->id);
dd($category_ids);
}
}
public function GetAllChildCategoryIDS($category_id) {
$ids_array = Category::where('parent_id',$category_id)->pluck('id')->all();
foreach($ids_array as $ida) {
$temp_ids=$this->GetSubCategoryIDS($ida);
if(count($temp_ids)) {
$ids_array[]=$temp_ids;
}
}
if(!empty($ids_array)) {
$ids_array=$this->array_flatten($ids_array);
}
return $ids_array;
}
public function GetSubCategoryIDS($category_id) {
$ids_array = Category::where('parent_id',$category_id)->pluck('id')->all();
return $ids_array;
}
public function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $this->array_flatten($value));
} else {
$result[$key] = $value;
}
}
return $result;
}
结果
array:20 [▼
0 => 22
1 => 23
2 => 24
3 => 25
4 => 26
5 => 27
6 => 35
7 => 36
8 => 37
9 => 38
10 => 39
11 => 40
12 => 41
13 => 28
14 => 29
15 => 30
16 => 31
17 => 32
18 => 33
19 => 34
]
您可以使用递归关系,以便:
公共函数childs(){
返回$this->hasMany(Category::class);
}
公共函数递归Childs(){
返回$this->childs()->with('recursiveChilds');
}
然后您可以访问任意n级别的child:
foreach($category->recursiveChilds作为$level\u 1\u child){
foreach($level\u 1\u child->recursiveChilds as$level\u 2\u child){
[...]
}
}
如果要收集所有子对象,可以使用以下方法:
public static function flattenChilds($parent)
{
$result = collect([]);
foreach ($parent->recursiveChilds as $child) {
$result->push($child);
$result = $result->merge(static::flattenChilds($child));
}
return $result->filter();
}
您可以使用递归关系,以便:
公共函数childs(){
返回$this->hasMany(Category::class);
}
公共函数递归Childs(){
返回$this->childs()->with('recursiveChilds');
}
然后您可以访问任意n级别的child:
foreach($category->recursiveChilds作为$level\u 1\u child){
foreach($level\u 1\u child->recursiveChilds as$level\u 2\u child){
[...]
}
}
如果要收集所有子对象,可以使用以下方法:
public static function flattenChilds($parent)
{
$result = collect([]);
foreach ($parent->recursiveChilds as $child) {
$result->push($child);
$result = $result->merge(static::flattenChilds($child));
}
return $result->filter();
}
这回答了你的问题吗@matiaslauriti这是可行的,但它只返回子类别。我想要的是子类别以及它的子类别等等,直到传递的父idIt的子类别的最后一级与我共享的相同,您必须使用
hasMany
或belongTomany
,这是否回答了您的问题@matiaslauriti这是可行的,但它只返回子类别。我想要的是子类别及其子类别等等,直到通过的父idIt的子类别的最后一级与我共享的相同,您必须使用hasMany
或belongTomany
来实现它本身…不,我不能使用它,因为我可能不知道在最后一级之前应该有多少个n级,而不是嵌套的foreach循环。如果您只想有一个集合,可以展平所有集合(我编辑了我的答案)不,我不能使用它,因为我可能不知道有多少个n级,直到最后一级才应该得到,而不是嵌套的foreach循环。如果您只想有一个集合,可以展平所有集合(我编辑了我的答案)