【发布时间】:2021-12-26 19:14:53
【问题描述】:
我有两个表 User 和 Post 由自定义多对多表链接,例如:
model User {
id Int @id @default(autoincrement())
name String
enabled Bool
posts users_to_posts[]
}
model Post {
id Int @id @default(autoincrement())
name String
enabled Bool
users users_to_posts[]
}
model user_to_post {
user user? @relation(fields: [user_id], references: [id])
user_id Int
post post? @relation(fields: [post_id], references: [id])
post_id Int
@@id([user_id, post_id])
}
我正在尝试根据必须启用用户和帖子的帖子 ID 列表获取用户列表。
到目前为止,如果他们在给定的帖子数组中有帖子,我可以获得已启用的正确用户,但我无法检查帖子是否已启用,也无法过滤帖子(我得到所有帖子如果匹配,则与用户关联)
这是我拥有的(几乎)工作代码:
import { PrismaClient, Prisma } from '@prisma/client'
const prisma = new PrismaClient()
export default async function handler(req, res) {
if (req.method !== 'POST') {
res.status(400).send({ message: 'Only POST requests allowed for this route' })
} else {
const { posts_id } = req.query
const posts_array = posts_id.split(",").map(function(item) {
return parseInt(item)
})
const ret = await prisma.user.findMany({
where: {
enabled: true,
post: { some: { post_id: { in: posts_array } }, },
},
include: {
_count: { select: { post: true } }
post: { select: { post: true }, },
},
})
res.status(200).send(ret)
// ...
}
}
我仍在努力了解如何在不依赖打字稿的情况下进行多个嵌入式选择以使查询正常工作(女巫远非理想)
【问题讨论】:
标签: typescript next.js prisma