Search code examples
prisma

PrismaJS: Sort by likes


I have two prisma tables that look like below, how could I sort the posts with the most likes:

model Post {
  id        String   @id @default(cuid())
  title     String   @default("")
  content   String   @default("")
  published Boolean  @default(false)
  userId    String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  imageUrl  String   @default("")
  prompt    String   @default("")
  user      User?    @relation(fields: [userId], references: [id])
  likes     Like[]
}

model Like {
  id        String   @id @default(cuid())
  user      User     @relation(fields: [userId], references: [id])
  userId    String
  post      Post     @relation(fields: [postId], references: [id])
  postId    String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@unique([userId, postId]) // Add a unique constraint
}

Any help would be greatly appreciated.


Solution

  • You could try this:

    const postsWithLikes = await prisma.post.findMany({
      orderBy: {
        likes: {
          _count: 'desc'
        },
      }
    });
    

    See docs for example: https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#sort-user-by-the-posts-count