Strapi Version: Latest
Operating System: Ubuntu
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.
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.
Appreciate any help I can get, thank you!
Anyone who feel they could help? Been struggling with that issue for a while now and it’s really driving me mad.
It seems like something so simple to do, yet I cannot find how to do it with a custom controller…
Thanks very much in advance!
Note: If I cannot manage to do it programmatically, I’ll just create a number field on the Category collection type that I’ll update manually…
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…
So from the answer here.
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
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
Here is what I was able to do.
I fetch all the categories and populate the products/apps for each category. I then map over the category array and update the field ‘numberOfApps’.
Thanks a lot for your help!
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!