How do I get all children that fall under a parent

2019-04-07 21:08发布

In my database, I have a Categories table. Categories can have parent categories, making it a recursive relationship

I also have a products table. Each product falls under a category.

Say, for example, I have a tree that looks like this:

Category
    Sub-Category 1
        Sub-Sub-Category 1
            Product 1
            Product 2
            Product 3
            Product 4
        Sub-Sub-Category 2
            Product 5
            Product 6
            Product 7
            Product 8
    Sub-Category 2
        Sub-Sub-Category 3
            Product 9
            Product 10
            Product 11
            Product 12

If I do $SubCategory1->products, I want it to give me Products 1-8

If I do $SubSubCategory3->products, I want it to give me products 9-12

If I do $Category->products, I want it to give me all products

Basically, I want the category to give all products that fall under it

4条回答
干净又极端
2楼-- · 2019-04-07 21:23

Suppose your Model name is Category

Create a function on Category model

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

Using above method on your controller

$categories = Category::with('children')->where('parent_id',0)->get();
查看更多
男人必须洒脱
3楼-- · 2019-04-07 21:28

please try the below Has Many Through relation and post the result

class Category extends Model
{
    public function products()
    {
        return $this->hasManyThrough(
            'App\Product', 'App\Category',
            'parent_id', 'catergory_id', 'id'
        );
    }
}

Then you can use $category->products; to find your products

查看更多
Explosion°爆炸
4楼-- · 2019-04-07 21:32

This way works very good:

class One extends Model {
    public function children()
    {
        return $this->hasMany(self::class, 'parent_id');
    }

    public function grandchildren()
    {
        return $this->children()->with('grandchildren');
    }
}
查看更多
SAY GOODBYE
5楼-- · 2019-04-07 21:44

After hoping to find an answer that uses Laravel nicely, I ended up giving up and just writing the code to do what I wanted myself, and it ended up smaller than I anticipated.

public function all_products()
{
    $products = [];
    $categories = [$this];
    while(count($categories) > 0){
        $nextCategories = [];
        foreach ($categories as $category) {
            $products = array_merge($products, $category->products->all());
            $nextCategories = array_merge($nextCategories, $category->children->all());
        }
        $categories = $nextCategories;
    }
    return new Collection($products); //Illuminate\Database\Eloquent\Collection
}
查看更多
登录 后发表回答