Prisma 订单帖子基于喜欢

Prisma order posts based on likes

我有一个 Post 型号:

model Post {
  id      String @id @default(auto()) @map("_id") @db.ObjectId
  title   String
  content String
  likes   Like[]
}

还有一个喜欢的模特:

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
}

我想根据 post 收到的喜欢(不是不喜欢)的数量来订购 post。 类似于:

prisma.post.findMany({
    orderBy: {
      likes: {
        _count: {
          where: {
            likeType: "like",
          }
        }
      }
    }
  })

您可以按 2.19.0 中的关系按聚合(包括计数)进行排序。 但它目前是 not possible 到 return 关系本身的计数。 分离喜欢和不喜欢的模型简化了查询模式。

const orderedPosts = await prisma.post.findMany({
  orderBy: {
    likes: {
      count: 'asc'
    }
  }
})