Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all children that fall under a parent in eloquent?

In my database, I have a Categories table. Categories can have parent categories, making it a recursive relationship

I also have a products table. Each product falls under a category.

Say, for example, I have a tree that looks like this:

Category
    Sub-Category 1
        Sub-Sub-Category 1
            Product 1
            Product 2
            Product 3
            Product 4
        Sub-Sub-Category 2
            Product 5
            Product 6
            Product 7
            Product 8
    Sub-Category 2
        Sub-Sub-Category 3
            Product 9
            Product 10
            Product 11
            Product 12

If I do $SubCategory1->products, I want it to give me Products 1-8

If I do $SubSubCategory3->products, I want it to give me products 9-12

If I do $Category->products, I want it to give me all products

Basically, I want the category to give all products that fall under it

like image 256
botmin Avatar asked Jul 05 '16 04:07

botmin


1 Answers

After hoping to find an answer that uses Laravel nicely, I ended up giving up and just writing the code to do what I wanted myself, and it ended up smaller than I anticipated.

public function all_products()
{
    $products = [];
    $categories = [$this];
    while(count($categories) > 0){
        $nextCategories = [];
        foreach ($categories as $category) {
            $products = array_merge($products, $category->products->all());
            $nextCategories = array_merge($nextCategories, $category->children->all());
        }
        $categories = $nextCategories;
    }
    return new Collection($products); //Illuminate\Database\Eloquent\Collection
}
like image 132
botmin Avatar answered Oct 03 '22 00:10

botmin