P
Prisma•2w ago
Salmon Bhai

How do I get the count in nested relations.

Here I am trying to retrieve comment count for every post. How would I go about it?
const posts = await prisma.posts.findMany({
where: {
userId,
},
orderBy: [
{ startDate: 'asc' },
],
select: {
id: true,
title: true,
image: true,
publish: true,
comments: {
_count: {
id: true
}
}
}
});
const posts = await prisma.posts.findMany({
where: {
userId,
},
orderBy: [
{ startDate: 'asc' },
],
select: {
id: true,
title: true,
image: true,
publish: true,
comments: {
_count: {
id: true
}
}
}
});
2 Replies
Prisma AI Help
Prisma AI Help•2w ago
You opted for speed from this bot. Let's conjure up an answer right now! To get the count of comments for each post in a nested relation, you need to slightly modify your query. The correct way to do this in Prisma is by using the _count field at the top level of the select statement for the comments relation. Here's how you can adjust your query:
const posts = await prisma.posts.findMany({
where: {
userId,
},
orderBy: [
{ startDate: 'asc' },
],
select: {
id: true,
title: true,
image: true,
publish: true,
_count: {
select: {
comments: true
}
}
}
});
const posts = await prisma.posts.findMany({
where: {
userId,
},
orderBy: [
{ startDate: 'asc' },
],
select: {
id: true,
title: true,
image: true,
publish: true,
_count: {
select: {
comments: true
}
}
}
});
In this modified query, we've moved the _count to the top level of the select statement and specified that we want to count the comments relation. This approach is documented in the Prisma documentation on counting relations. The result will include a _count field for each post, containing the number of comments for that post. It's worth noting that this feature became generally available in Prisma version 3.0.1. If you're using an earlier version, you might need to update Prisma to use this feature. Prisma Documentation: Count relations 🤔 Alright, thanks for letting us know that there's still some help needed. A team member will reply to you shortly. In the meantime, please let us know any additional info, questions, or which parts of the answer may need clarification.
Nurul
Nurul•2w ago
Hey! Isn't this what you are looking for? If not, can you share the posts and comment model and elaborate on what you are trying to achieve?
Aggregation, grouping, and summarizing (Concepts) | Prisma Document...
Use Prisma Client to aggregate, group by, count, and select distinct.

Did you find this page helpful?