How to create nested categories in V4

Hello,
How do you create a collection with nested categories such as
Food

Desserts

Cookies
Cakes
Pies

Is there any documentation you can point to? What I’ve read so far makes it seem like children categories will all be at the same level as the parent categories.

Many thanks in advance.

2 Likes

Hi,

You can achieve by using relational fields.

Ex: create Collection LIke,

Food - categories.

Categories - Mains, Deserts.

Food has relation with categories.

Categories has relation with - Mains,Desert.

For more please refer the strapi documentation https://docs.strapi.io/user-docs/latest/content-manager/writing-content.html

creating multiple collection is not practical. since you will have to create new collection for every level

the deeper nested you go, the more collection you will have…

i prefer to have 1 collection only:

  1. Create collection “Category”
  2. Add relational field called “parent”. this field is “many-to-one relation” with the same “Category” collection. (it will read as “Category has many Categories” in strapi)

now when you enter the data:

enter “Desserts” and leave the parent field blank
Enter “Cookies” and choose “Deserts” from the Parent field drop down

To get your data in the api, you should populate the parent field

and that’s it …now u can add as many levels as you want.

Note: if you want the same sub-category falls under different categories (for example category Diet under Food and under Sweets) then choose many-to-many relation

1 Like

Thank you for sharing this Vipul.

Hi Zorox,
This is the solution that works best for what we were looking for. Many thanks!

Hi, does it work also if doing belongs to many? so we can have also the parent category inside each category…
Because as you said you can have children but in rest api there will be visible children separately also.

I found another way that seems to be more clear

You can create a reaction category (parent) - has many - category (children)

That way you can create a category like Fashion
Another one like Male with parent Fashion

when you see the Fashion category will note that the field children will point to the Male and in Male category you will see Fashion as parent, you can also do it to Male, creating t-shirts with male parent, and so on…