#How to get the sum of a nested relations.

4 messages · Page 1 of 1 (latest)

lime escarpBOT
#

You've gone full bot mode! Let me fetch that AI answer for you ASAP.

lime escarpBOT
# lime escarp You've gone full bot mode! Let me fetch that AI answer for you ASAP.

Based on the knowledge sources provided, it appears that Prisma does not currently support getting the sum of nested relations in the way you're attempting in your query. However, I can provide some information on what is possible and suggest an alternative approach.

Prisma does support counting nested relations using the _count field, which you're already using correctly in your query for the replies field. However, for summing values in nested relations (like you're trying to do with votes.noOfVotes), there isn't a direct way to do this in a single query as of the latest information available in the provided sources.

The closest feature to what you're looking for is the ability to count relations, which is described in the Prisma docs on relation queries:

const relationCount = await prisma.user.findMany({
  include: {
    _count: {
      select: { posts: true },
    },
  },
})

However, this doesn't extend to summing values within those relations.

As an alternative approach, you might need to perform the summation in your application code after fetching the data. You could modify your query to include the votes data and then calculate the sum manually:

const posts = await prisma.events.findMany({
  where: {
    userId,
  },
  select: {
    id: true,
    title: true,
    image: true,
    comments: {
      select: {
        active: true,
        _count: {
          select: {
            replies: true
          }
        },
        votes: {
          select: {
            noOfVotes: true
          }
        }
      }
    }
  },
});

// Then calculate the sum in your application code
const postsWithVoteSums = posts.map(post => ({
  ...post,
  comments: post.comments.map(comment => ({
    ...comment,
    votesSum: comment.votes.reduce((sum, vote) => sum + vote.noOfVotes, 0)
  }))
}));

It's worth noting that there is an open feature

lime escarpBOT
lament birch
#

What is an open feature