The easiest would be to add a parent category column to your table, that ways you can group them.
May 9, 2024
8
Level 1
How to count the number of related posts to a category tree?
I'm trying to count the number of products in each category. I do recursion and write thousands of lines of code. I think I'm doing something wrong)))
Can you tell me how to correctly implement this calculation? There is a tree of categories, the top categories have parent_id = null, all child categories have a parent_id that matches the parent's "category_id" string.
Example:
Clothes (quantity not specified) //need 26
Jackets and windbreakers (quantity not specified) //need 26 (23+3)
Jackets (5) //need 23 (5+10+8)
Long sleeve jackets (10) // Ok 10 - no child categories
Short sleeve jackets (8) // Ok 8 - no child categories
Windbreakers (3) // Ok 3 - no child categories
Shoes (quantity not specified)
...
You need to somehow go through the collection and sum up the number of products of all child categories.
public function recount()
{
$categories = Category::select('id', 'category_id', 'parent_id')->withCount('products')->get();
dd($categories);
}
I get the collection like this:
Illuminate\Database\Eloquent\Collection {#1660 ▼
#items: array:51 [▼
0 => App\Models\Category {#1659 ▼
...
#attributes: array:4 [▼
"id" => 30
"category_id" => 1
"parent_id" => null
"products_count" => 0
]
...
}
1 => App\Models\Category {#1658 ▼
...
#attributes: array:4 [▼
"id" => 31
"category_id" => 2
"parent_id" => null
"products_count" => 0
]
...
}
2 => App\Models\Category {#1657 ▼
...
#attributes: array:4 [▼
"id" => 32
"category_id" => 21
"parent_id" => 2
"products_count" => 0
]
...
}
3 => App\Models\Category {#1656 ▼
...
#attributes: array:4 [▼
"id" => 33
"category_id" => 211
"parent_id" => 21
"products_count" => 0
]
...
}
4 => App\Models\Category {#1655 ▼
...
#attributes: array:4 [▼
"id" => 34
"category_id" => 212
"parent_id" => 21
"products_count" => 0
]
...
}
5 => App\Models\Category {#1654 ▼
...
#attributes: array:4 [▼
"id" => 36
"category_id" => 2111
"parent_id" => 211
"products_count" => 15
]
...
}
Please or to participate in this conversation.