如何根据类别id获取laravel中所有子类别id?

问题描述 投票:0回答:1

我试图从顶层类别到最底层子类别递归地获取所有子类别 id。我为每个类别设置了一个父 ID,对于最上面的类别,我使用零作为父类别。我正在获取子类别列表,但不是全部。请帮忙。

控制器代码

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
]
php laravel
1个回答
2
投票

您可以使用递归关系 a so :


public function childs(){
    return $this->hasMany(Category::class);
}

public function recursiveChilds(){
   return $this->childs()->with('recursiveChilds');
}

然后你就可以访问任意n层的子级了:

foreach($category->recursiveChilds as $level_1_child){
     foreach($level_1_child->recursiveChilds as $level_2_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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.