为了账号安全,请及时绑定邮箱和手机立即绑定

类别和子类别的集合?

类别和子类别的集合?

PHP
汪汪一只猫 2023-12-15 15:31:36
类别表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 包括整个集合,最终结果有包含其本身的集合。有什么想法吗?
查看完整描述

2 回答

?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

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

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

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

要不就

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

你也可以用祖先代替后代 就这么简单
[1]:https://github.com/lazychaser/laravel-nestedset


查看完整回答
反对 回复 2023-12-15
?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

我建议将逻辑转移到相关类中,以便更容易理解您在做什么。


控制器:

    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.*


查看完整回答
反对 回复 2023-12-15
  • 2 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信