Search code examples
phplaravellaravel-5.3recursive-query

Laravel return all the ids of descendants


How do I return all the ids of AllSubSections (all levels)

class Section extends Model
{
    public function Ads()
    {
        return $this->hasMany(Ad::class);
    }

    public function AllSubSections()
    {
        return $this->SubSections()->with('AllSubSections');
    }

    public function SubSections()
    {
        return $this->hasMany(Section::class);
    }

    public function Parent()
    {
        return $this->belongsTo(Section::class);
    }
}

what am currently doing is :

$section = Section::where('name', 'Properties')->first();
$subSections = $section->AllSubSections;
$subSections->pluck('id')

but it only returns the 1st level not all the levels.


Solution

  • Here is what I came with:

    use Illuminate\Support\Collection;
    
    class Section
    {
        public function children ()
        {
            return $this->hasMany(Section::class,);
        }
    
        public function parent ()
        {
            return $this->belongsTo(Section::class);
        }
    
        public function getAllChildren ()
        {
            $sections = new Collection();
    
            foreach ($this->children as $section) {
                $sections->push($section);
                $sections = $sections->merge($section->getAllChildren());
            }
    
            return $sections;
        }
    }
    

    As you can see, getAllChildren is a recursive function. It contains a loop over the section children that adds to the collection the current child and calls itself again on this child.

    You can then use:

    $section->getAllChildren()->pluck('id');
    

    And you will get all your children ids.

    I hope I am responding to the question!