【问题标题】:Laravel Get All Children Under ParentLaravel 获取父级下的所有子级
【发布时间】:2019-01-31 22:44:24
【问题描述】:

在我的数据库中,我有类别,它们可以有子类别。类别也有产品。例如:

Category
    Sub-Category 1
      Product 1
        Sub-Sub-Category 1
            Product 2
            Product 3

类别模型

public function childs()
{
    return $this->hasMany('App\Category', 'parent_id', 'id');
}

public function products()
{
    return $this->belongsToMany('App\Products');
}

我的问题是,如果我做 $Category->products,我希望它给我所有的产品。如果我执行 $Sub-Sub-Category-1,它会给我产品 2 和产品 3。感谢您的帮助。

【问题讨论】:

  • 没有关系可以做到这一点,您可能需要某种递归函数。

标签: php laravel relationship


【解决方案1】:

只是根据daven 评论的示例递归方法。

它没有经过测试,但其背后的想法是抓取所有子类别并递归选择所有产品。

    public function allProducts()
    {
        //call recursive method to append all children categories
        return $this->getAll([$this])
            //select category products as each item
            ->pluck('products')
            //flatten products into one dimension array
            ->flatten()
            //remove repeated products
            ->unique();
    }

    public function getAll($categories)
    {
        //appending categories array
        $append = collect();
        //walk-through input categories
        foreach ($categories as $category)
        {
            //if category has children add them to $append
            if ($category->childs()->count())
            {
                $append->merge($category->childs);
            }
        }
        //if there were children categories, also add their children to $append
        if ($append->count())
        {
            $append = $this->getAll($append);
        }
        //merge children and categories
        return $categories->merge($append);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2017-12-08
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多