dimanche 5 novembre 2023

Get all children categories of a collection of categories without using foreach in Laravel

so I have this codes in my Category model. What it does is, you give it a single category collection and it will return all children category ids of that category in a one dimensional array of ids that can be used in a whereIn query.

private $descendants = [];

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

public function children()
    {
        return $this->subcategories()->with('children');
    }

public function hasChildren(){
        if($this->children->count()){
            return true;
        }

        return false;
    }

public function findDescendants(Category $category){
        $this->descendants[] = $category->id;

        if($category->hasChildren()){
            foreach($category->children as $child){
                $this->findDescendants($child);
            }
        }
    }

public function getDescendants(Category $category){
        $this->findDescendants($category);
        return $this->descendants;
}

Usage:

$category = Category::where('id',$id)->first();
$children_ids = [];
$children_ids = $category->getDescendants($category);

It works. It is very useful in my filter. But when it comes to getting children ids of multiple categories, I had to use foreach loop and I had to call getDescendants multiple times thus creating multiple queries. What I want to accomplish are:

  1. To improve performance how to do it in a single query without the need of using foreach loop? Where I want to feed it not just a single category but a collection of categories, and then it should return all children category ids of those categories.
  2. How to return not just children ids but entire collection of children categories?

What usage I had in mind (please feel free to suggest a better approach)

Getting children ids from category collections:

$category = Category::where('parent_id',$id)->get();
$children_ids = [];
$children_ids = $category->getDescendants($category);

Getting children collection from category collections.

$category = Category::where('parent_id',$id)->get();
$children_ids = [];
$children_ids = $category->getDescendants($category);

Please help me accomplish this. Thank you.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/iWhNlZH
via IFTTT

Aucun commentaire:

Enregistrer un commentaire