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.
countStudies: Articles(
where: {
category: { equals: "studies" }
slug: { not_in: $excludeSlugs }
noCard: { not_equals: true }
_status: $_status
}
page: $page
limit: $limit
sort: "-publishDate"
) {
totalDocs
}
countTrendsReports: Articles(
where: {
category: { equals: "trends-reports" }
slug: { not_in: $excludeSlugs }
noCard: { not_equals: true }
_status: $_status
}
page: $page
limit: $limit
sort: "-publishDate"
) {
totalDocs
}
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.
@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!
@jacobsfletch That's right. The solution I proposed is the way I have seen that some other CMS manage it, but I understand it's a different topic.
However your proposed solution is a good option. I personally use MongoDB aggregations in a custom route to perform these counts.
Great work on Payload btw! My favorite CMS by far
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 Articles
collection there's a category
field and on the Category
collection there's a articles
field with hasMany: true
.
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.