0
votes

i have a categories table with parent_id to store categories and subcategories. this categories can be multi level which means a category can have subcategories and each subcategory can have subcategories and so on. and it is dynamic so the levels number in not limited. i defined a function in Category model with name as below:

public function childs()
{
    return $this->hasMany(Category::class, 'parent_id');
}

Now i want to eager load the categories with subcategories. the code

$cats = Category::with('childs')->get();

works greate but it gets just one level of subcategories and i want to eager load all levels. something like

$cats = Category:with('childs')->with('childs')... ->get();

is there any way to do that? to get all category levels? if there isn't, how to get all levels of subcategories in one collection without eager loading?

2

2 Answers

0
votes

You could use this to load all subcategories

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

    public function childrenTree()
    {
        return $this->children()->with('childrenTree');
    }
}
0
votes

Just call your relation withing your relation. I mean recursively. Try this code:

class Category extends Model
{
   public function subCategory()
   {
      return $this->hasMany(Category::class, 'parent_id')->with('subCategory');
    }
}