I have a Post model:
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String
likes Like[]
}
And a Like model:
model Like {
id String @id @default(auto()) @map("_id") @db.ObjectId
user User @relation(fields: [userId], references: [id])
userId String @db.ObjectId
postId String @db.ObjectId
post Post @relation(fields: [postId], references: [id])
likeType LikeType
}
enum LikeType {
like
dislike
}
I want to order posts based on the number of Likes (not dislikes) a post receives.
Something like:
prisma.post.findMany({
orderBy: {
likes: {
_count: {
where: {
likeType: "like",
}
}
}
}
})
>Solution :
You can sort by a relation from 2.19.0 by aggregates including count.
But it’s currently not possible to return the count of a relation itself.
Separating the models for likes and dislikes simplifies the query pattern.
const orderedPosts = await prisma.post.findMany({
orderBy: {
likes: {
count: 'asc'
}
}
})