我想知道当一个过滤器是一种关系时,我如何在 Prisma 2 中使用多个过滤器。我搜索具有特定 ID 和特定作者的帖子(安全原因)。
我读了documentation我试着申请这个:
const postExists = await prisma.post.findMany({
where: {
AND: [
{
id: {
equals: parseInt(args.id, 10), // args.id => 770
},
},
{
author: {
id: {
equals: parseInt(userId, 10), // userId => 584
},
},
},
],
},
})
在我的数据库中我有这个:
但如果我不是作者(例如,作者 id 1),我会找到我的帖子
const postExists = await prisma.post.findMany({
where: {
AND: [
{
id: {
equals: parseInt(args.id, 10), // args.id => 770
},
},
{
author: {
id: {
equals: parseInt(userId, 10), // userId => 1
},
},
},
],
},
})
在我的 schema.prisma 中我有这个:
model Post {
content String?
createdAt DateTime @default(now())
fk_user_id Int
id Int @default(autoincrement()) @id
published Boolean @default(false)
title String
author User @relation(fields: [fk_user_id], references: [id])
@@index([fk_user_id], name: "fk_user_id")
}
model User {
email String @unique
id Int @default(autoincrement()) @id
name String?
password String @default("")
Post Post[]
Profile Profile?
}
最佳答案
您的第二个过滤器应该使用 fk_user_id
而不是 author
。
字段author
和posts
分别是Post
和User
中的虚拟字段。它们被称为关系字段。关系字段在 Prisma 级别定义模型之间的连接,它们不存在于实际的数据库表中。
fk_user_id
代表创建Post
的作者(User
)。
此外,由于在您的情况下,您总是会得到一个 Post
作为结果,请使用 findFirst()
而不是 findMany()
。这样,您就不必处理 Array
。
修改后的代码如下:
const postExists = await prisma.post.findFirst({
where: {
AND: [
{
id: {
equals: parseInt(args.id, 10)
}
},
{
fk_user_id: {
equals: parseInt(userId, 10)
}
},
],
},
})
请注意,我们删除了两个级别 author:
和 id:
并且只插入了一个级别 fk_user_id:
。我们还删除了不必要的逗号。
https://stackoverflow.com/questions/62539472/
相关文章:
firebase - 使用 Firebase 通过 OAuth2 创建登录名时指定 UserId 格
python - 如何防止vscode/ms-python清除测试结果?
javascript - 为什么 useState 不在单元测试(Jest、Enzyme)中重新渲染
python - Pandas 的 Mypy/typeshed stub
java - 如何获取 Azure blob 下载中的 blob 下载进度
amazon-web-services - 由于 Amplify 上的身份验证 token 过期较短
ios - Safari 或 IOS 中视频的 aws-sdk getSignedUrl 不起作用