0
votes

i have category table, and sub categories also in same table... if some category have null parent_id its top node category. table basic fields like this:

---------------------
|id |name |parent_id|
---------------------

I just need to get all childs ids in minimum quarry execution: eg:

Category::find(2)->allChildIds(); //result like [3,4,6,10,....]

i have this relationship added:

  public function parent(){
        return $this->belongsTo(Category::class);
    }

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

thank you

1
select * from table where parent_id = 2 .................... ?Joel M
its only give sub categories only have parent_id =2. a sub category also can have more subcategories.. like tree structurevidur

1 Answers

0
votes

I stumbled before into a similar issue and I had to use recursion

the function is like so :

$allChildren = []; 
/*
$categories => you're categories list that you query from the database 
&$allChildren => is a pointer to array to store all children id's 
$parent->id => your category id that you like to have all children of it 
*/
function getAllChildren($categories, &$allChildren, $parent_id = null)
    {
        //filter only categories to have the direct children under current "parent"
        $cats = $categories->filter(function ($item) use ($parent_id) {
            return $item->parent_id == $parent_id;
        });

        //loop through each child
        foreach ($cats as $cat)
        {
            // Add each child to the allChildren array
            array_push($allChildren,$cat->id);
            //go deeper to have the children of that child by sending its id as a 
            // parent id
            $this->getAllChildren($categories, $allChildren, $cat->id);
        }
    }

Hope that helps!