I have a PRODUCT collection type & a CATEGORY collection type. I have added a relation between the two collection types.
When I fetch the categories from my frontend, I would like to know the number of PRODUCTS that are linked to each category. This info is very often displayed on many e-commerce.
How can I best do that?
Fetching all categories & all the products that are linked to each category. This seems like OVERKILL & sending a bunch of useless data to my frontend.
Custom controller? I tried using strapi.entityService.count but it gives me back the total number of CATEGORIES, not the number of PRODUCTS associated to each category.
this seems like such a trivial thing to do but as a beginner I struggle so much with the strapi doc. I am pretty sure I need to do a custom controller but I don’t know how to get the desired result…
I would maybe then suggest to grab it either A) On boot or use a CRON job.
Fetch the data you want as in what you said in 1.
You can then populate a field of the amount you want.
You could also do the other way around, query all the products that has a category of what you want.
A last resort would be to maybe use a custom controller as suggested by other members.
you can then populate the products for what you are getting, count the length of that array and make that part of the response before returning {data, meta}
PS: It seems to be working but I feel it’s not very efficient. If anyone has any suggestions regarding improvements, please feel free to leave a message!