I have following 2 Tables:
Ad: {id, title, category_id} Category: {id, name, parent_id}
Table 1: Ad
---|----------------------------|------------
id | title | category_id
---|----------------------------|------------
1 | Ad in Cars category | 2
2 | Another Ad in Cars category| 2
3 | Ad in Vehicles category | 1
Table 2: Category
---|-----------|-----------
id | name | parent_id
---|-----------|-----------
1 | Vehicles | NULL
2 | Cars | 1
Now I need to fetch Categories and count of ads in each category. Also, if a category has ads in child categories, then the count of ads for a parent category should also include ads belonging to child category.
So if I fetch the count of ads in Vehicle category, I should get:
Category | Count
---------|-----------
Vehicles | 3
And if I fetch count of ads in Cars Category, I should get:
Category | Count
---------|-----------
Cars | 2
How do I achieve this in Laravel? I'm using Laravel 5.4.
Thanks!
via Rishab