我正在尝试 findMany() 用户和 orderBy 他们的帖子数。我在文档中确切地找到了如何做到这一点,它可以工作,除了它将有 0 个帖子的用户计为 +infinity。 orderBy: {posts: {count: asc}}
例如,从有 1 个帖子的用户开始按升序排列,直到有很多帖子的用户,但最后一个用户有 0 个帖子。下降时反之。
我使用 postgres 作为提供者,我真的不知道如何用谷歌搜索这个问题,并为这个问题命名。请帮忙。
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
user User @relation(fields: [userID], references: [id])
userID Int
}
await prisma.user.findMany({
orderBy: {
posts: {
count: 'desc',
},
},
});
小测试的降序输出。您可以看到帖子计数按 0 2 1 排序(按升序排列,其输出顺序为 1 2 0):
[
{ id: 3, _count: { posts: 0 } },
{ id: 1, _count: { posts: 2 } },
{ id: 2, _count: { posts: 1 } }
]