类别和子类别的集合?

类别表


id| name               | parent_id   

--|------------------  |-----------  

1 | Clothing           |  null   

2 | Shirt              |  1   

3 | Sports shirt       |  2   

4 | Men's sports shirt |  3   

5 | Hat                |  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 包括整个集合,最终结果有包含其本身的集合。

有什么想法吗?


汪汪一只猫
浏览 64回答 2
2回答

侃侃尔雅

该指南有些有效,但最后我使用了一个有用的包 [lazychaser / laravel-nestedset][1]这使得使用类别和子类别变得更加容易$categories = Category::with('descendants')->get()->toTree();要不就$categories = Category::with('descendants')->get()->toFlatTree();你也可以用祖先代替后代 就这么简单[1]:https://github.com/lazychaser/laravel-nestedset

海绵宝宝撒

我建议将逻辑转移到相关类中,以便更容易理解您在做什么。控制器:    public function get(Category $category): Collection    {       return (new GetAllCategories($category))->handle();    }模型    public function children(): HasMany    {        return $this->hasMany(Category::class, 'parent_id', 'id');    }GetAllCategories 操作类。这个类将循环遍历每个孩子并返回相关的孩子。    public function handle(): Collection    {          return $this->buildCategory($this->category);    }    protected function buildCategory(Category $category): Collection    {          return collect([            'category' => $category,            'children' => $this->getChildren($category),        ]);    }       protected function getChildren(Category $category): Collection    {          return $category                ->children                ->map(fn($child) => $this->buildCategory($child));    }   我没有添加use语句、__consturct方法或路由绑定。我假设您使用的是 php7.4 和 laravel 7.*
打开App,查看更多内容
随时随地看视频慕课网APP