亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

類別和子類別的集合?

類別和子類別的集合?

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條經驗 獲得超16個贊

該指南有些有效,但最后我使用了一個有用的包 [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 關注
  • 180 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號