1

I have a model Category which has a manyToMany relation with itself:

public function parentcategories()
{
    return $this->belongsToMany('App\Category', 'category_category', 'parent_category_id', 'category_id');
}

public function categories()
{
    return $this->belongsToMany('App\Category', 'category_category', 'category_id', 'parent_category_id');
}

What is the simplest way to get all of the descendant Categories?

For example:

Cat1
-Cat2
-Cat3
--Cat4
--Cat5
---Cat6
Cat7
-Cat8

If I click Cat1 I want to get Cat2-6, and if I click Cat3 I want to get Cat4-6.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
dbr
  • 1,037
  • 14
  • 34
  • Am I doing something wrong here? I thought this would be a common problem. – dbr Mar 02 '16 at 19:08
  • 1
    I think the word you're looking for is "hierarchy". Not specific to Eloquent, but this might be useful: http://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database. Also see this question: http://stackoverflow.com/questions/25051501/laravel-eloquent-get-n-level-hierarchy-records-from-self-referencing-table-with. Apparently there is a package that will implement the Nested Set Model for you, https://github.com/lazychaser/laravel-nestedset – alexw Mar 27 '16 at 21:52

0 Answers0