How can I correctly do joins with prisma? I have a...
# orm-help
s
How can I correctly do joins with prisma? I have a Post model that contains a list of Votes, and I'm trying to run a query that returns every post and also includes a field in each post object containing the sum of the amount field in every vote attached to that post
r
@Scratchyone Scratchyone ๐Ÿ‘‹ So given this schema:
Copy code
model Post {
  id    Int    @id @default(autoincrement())
  title  String
  votes Vote[]
}

model Vote {
  id     Int   @id @default(autoincrement())
  post   Post? @relation(fields: [postId], references: [id])
  postId Int?
}
Do you want something like this?
Copy code
[
 { title: "post 1", votes: { _count: 100 }
]
This can be done via:
Copy code
await prisma.post.findMany({
    include: { _count: { select: { votes: true } } },
  })
s
@Ryan thank you! Sadly my vote system is a tad more complicated than that, a vote also contains an amount value of either 0, -1, or 1 (empty vote, downvote, upvote), so I need to be able to sum that value to figure out the actual vote count
heres the js version im using right now
but that doesnt scale because it requires loading all the votes into memory to count them
r
In that case, a raw query with
prisma.$queryRaw
and using the
case
keyword would be your best bet as thatโ€™s currently not supported in Prisma. It would be great if you could add a ๐Ÿ‘ on this request so that we can know the priority ๐Ÿ™‚
s
Thank you!!
๐Ÿ™Œ 2