How to create a nested-list of categories in Laravel?

后端 未结 6 1656
盖世英雄少女心
盖世英雄少女心 2020-12-08 17:34

How can I create a nested list of categories in Laravel?

I want to create something like this:

  • --- Php
  • ------ Laravel
6条回答
  •  春和景丽
    2020-12-08 17:54

    If someone needs a better answer look up my answer, it helped me, when I had faced with such a problem.

       class Category extends Model {
    
         private $descendants = [];
    
         public function children()
            {
                return $this->subcategories()->with('children');
            }
    
         public function hasChildren(){
                if($this->children->count()){
                    return true;
                }
    
                return false;
            }
    
         public function findDescendants(Category $category){
                $this->descendants[] = $category->id;
    
                if($category->hasChildren()){
                    foreach($category->children as $child){
                        $this->findDescendants($child);
                    }
                }
            }
    
          public function getDescendants(Category $category){
                $this->findDescendants($category);
                return $this->descendants;
            }
     }
    

    And In your Controller just test this:

    $category = Category::find(1);
    $category_ids = $category->getDescendants($category);
    

    It will result ids in array all descendants of your category where id=1. then :

    $products = Product::whereIn('category_id',$category_ids)->get();
    

    You are welcome =)

提交回复
热议问题