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

后端 未结 6 1640
盖世英雄少女心
盖世英雄少女心 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:50

    This function will return tree array:

    function getCategoryTree($parent_id = 0, $spacing = '', $tree_array = array()) {
        $categories = Category::select('id', 'name', 'parent_id')->where('parent_id' ,'=', $parent_id)->orderBy('parent_id')->get();
        foreach ($categories as $item){
            $tree_array[] = ['categoryId' => $item->id, 'categoryName' =>$spacing . $item->name] ;
            $tree_array = $this->getCategoryTree($item->id, $spacing . '--', $tree_array);
        }
        return $tree_array;
    }
    
    0 讨论(0)
  • 2020-12-08 17:53

    This also worked:

    View:

        $traverse = function ($categories) use (&$traverse) {
            foreach ($categories as $category) $traverse($cat->Children);
        };
        $traverse(array ($category));
    

    Model:

    public function Children()
    {
        return $this->hasMany($this, 'parent');
    }
    
    public function Parent()
    {
        return $this->hasOne($this,'id','parent');
    }
    
    0 讨论(0)
  • 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 =)

    0 讨论(0)
  • 2020-12-08 18:00

    you can solve this problem like this :

    class Category extends Model
    {
        public function categories()
        {
           return $this->hasMany(Category::class);
        }
    
        public function childrenCategories()
        {
           return $this->hasMany(Category::class)->with('categories');
        }
    
    }
    

    and get category with children like this :

    Category::whereNull('category_id')
        ->with('childrenCategories')
        ->get();
    

    notice : just rename parent_id column to category_id

    0 讨论(0)
  • 2020-12-08 18:06

    You can make a self-referential model:

    class Category extends Model {
    
        public function parent()
        {
            return $this->belongsTo('Category', 'parent_id');
        }
    
        public function children()
        {
            return $this->hasMany('Category', 'parent_id');
        }
    }
    

    and make a recursive relation:

    // recursive, loads all descendants
    public function childrenRecursive()
    {
       return $this->children()->with('childrenRecursive');
    }
    

    and to get parents with all their children:

    $categories = Category::with('childrenRecursive')->whereNull('parent')->get();
    

    Lastly you need to just iterate through the children until children is null. There can definitely be some performance issues with this if you are not careful. If this is a fairly small dataset that you plan to remain that way it shouldn't be an issue. If this is going to be an ever growing list it might make sense to have a root_parent_id or something to query off of and assemble the tree manually.

    0 讨论(0)
  • 2020-12-08 18:11

    Searching for something somehow in this area I wanted to share a functionality for getting the depth level of child:

        function getDepth($category, $level = 0) {
        if ($category->parent_id>0) {
            if ($category->parent) {
                    $level++;
                    return $this->getDepth($category->parent, $level);
                }
            }
           return $level;
        }
    

    Maybe it will help someone! Cheers!

    0 讨论(0)
提交回复
热议问题