Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prisma order posts based on likes

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
    }
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading