首页 > 解决方案 > 类别和子类别的集合?

问题描述

类别表

编号| 姓名 | parent_id   
--|-------------------- |------------  
1 | 服装 | 无效的   
2 | 衬衫 | 1   
3 | 运动衫 | 2   
4 | 男士运动衫| 3   
5 | 帽子 | 1

类别型号:

    public function child()
    {
        return $this->hasMany(Category::class, 'parent_id', 'id');
    }

    public function newRelation($allCategories){
        if ($this->child->isNotEmpty()) {
            $children = collect();
            $allCategories = $this->subCategories($children);
        }
        return $allCategories->unique();
    }

    public function subCategories($allCategories) {
        $this->child->map(function($item, $key) use(&$allCategories){
            $allCategories->push($item);
            if ($item->child->isNotEmpty()) {
                $allCategories->push($item->subCategories($allCategories));
            }
        });
        return $allCategories;
    }

控制器:

$allCategories = collect();
$category = Category::find(1);
$result = $category->newRelation($allCategories);

一些它是如何工作的,但在另一个集合中返回一些额外的数据集合,实际上在 subCategories 方法中每次返回 $allCategories 包括整个集合,最终结果有集合包括它自己。
任何想法?

标签: phplaravel

解决方案


该指导有些奏效,但最后我使用了一个有用的包 [lazychaser / laravel-nestedset][1]

这使得使用类别和子类别变得更加容易

$categories = Category::with('descendants')->get()->toTree();

要不就

$categories = Category::with('descendants')->get()->toFlatTree(); 

你也可以把祖先而不是后代放在很容易
[1]:https ://github.com/lazychaser/laravel-nestedset


推荐阅读