Is it possible to count posts/pages by group by a category field? #1588
-
I have a tab switch to show two different categories of articles with the total num shown in tab title. https://getjerry.com/data-and-studies Now I'm using two queries to fetch these two counts separately.
It works, but I'm wondering if there's a more elegant(one query) or extensible(if I need all categories) way to do this. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
I'm having the exact same situation. The only thing I could think of was if there was some sort of bi-directional field in the relationship between the collections. For example: In the Other CMS like Strapi and Directus handle this with the "one-to-one", "one-to-many" and "many-to-many" technique, which automatically maintains both fields I mentioned before as a nice relationship. However, I imagine that it's easier on those CMS because they use SQL databases but Payload uses MongoDB that's NoSQL. |
Beta Was this translation helpful? Give feedback.
-
@Stupidism there's currently no API for this, however, you could wire up your own custom endpoint to consolidate multiple queries. It would look like this: your front-end makes a single request to your Payload server, it uses the Local API to query "studies" and "trend reports" similarly to your example above, then it returns both results back to you in a single response. @ChrisGV04 I think what you're talking about to is slightly different, although a great idea. This is already some discussion around bidirectional/inversed relationships, check it out! |
Beta Was this translation helpful? Give feedback.
-
hi,I have encountered the same problem. Can you provide a complete example code?thank you! |
Beta Was this translation helpful? Give feedback.
@Stupidism there's currently no API for this, however, you could wire up your own custom endpoint to consolidate multiple queries. It would look like this: your front-end makes a single request to your Payload server, it uses the Local API to query "studies" and "trend reports" similarly to your example above, then it returns both results back to you in a single response.
@ChrisGV04 I think what you're talking about to is slightly different, although a great idea. This is already some discussion around bidirectional/inversed relationships, check it out!