假设我有一张桌子
User
有名字、Id和表格
Post
有名字和内容。这两个表通过多对多关系链接(一篇文章可以有多个用户/作者,每个用户可以有多篇文章)
例子:
model User {
id Int @id @default(autoincrement())
name String
posts users_to_posts[]
}
model Post {
id Int @id @default(autoincrement())
name String
users users_to_posts[]
}
model user_to_post {
user user? @relation(fields: [user_id], references: [id])
user_id Int
post signe? @relation(fields: [post_id], references: [id])
post_id Int
@@id([user_id, post_id])
}
我想做的是查询用户表,找出写文章最多的前10位用户。
但是,我不希望只返回user+post count的组合,而是完整返回用户、他的Id和他在返回的JSON中作为单独键写入的帖子数量
我尝试获取的示例(使用nextJS):
import { PrismaClient, Prisma } from '@prisma/client'
const prisma = new PrismaClient()
export default async function handler(req, res) {
const ret = await prisma.user.findMany({
include: {
posts: {
select: {
post: true
}
}
}
// include post count
// order by post count
// limit 10
});
res.status(200).json(ret)
}
正如您所见,我的表中没有“count”列,必须在查询过程中插入它
我现在最好的选择是解析获得的json(ret变量),并通过typescript完成所有工作,但这远远不够理想