【发布时间】:2021-10-17 21:57:36
【问题描述】:
我想用 id、slug、用户名、userId 参数查询帖子。查询中至少存在一个参数值。不需要全部。
const post = await prisma.post.findFirst({
where: {
OR: [
{
AND: [
{ published: true },
{
OR: [
{ id },
{
AND: [
{ slug },
{
author: {
profile: {
username
}
}
}
]
}
]
}
]
},
{
authorId: userId || undefined
}
]
},
...select
})
数据库数据(帖子):
[{id: 1, published: false}, {id: 2, published: true}]
查询参数为id: 1,但输出为:
{id: 2, published: true}
我的查询有什么问题吗?
Prisma 后模型:
model Post {
id String @id @default(cuid())
title String
body String
slug String
published Boolean
draft Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
}
用户模型:
model User {
id String @id @default(cuid())
name String
email String @unique
password String?
posts Post[]
profile Profile?
}
简介型号:
model Profile {
id String @id @default(cuid())
bio String?
author User? @relation(fields: [authorId], references: [id])
authorId String?
phone String?
username String?
}
【问题讨论】:
-
您能否更清楚地阐明您的要求,因为它有点模棱两可?您是说: 1. 在运行查询期间至少提供了 id、slug、username、userId 变量之一(其余变量未定义/为空)? 2. id、slug、username、userId 变量在查询过程中都是可用的,但只有其中一个需要与数据库中的条目匹配?在 2 的情况下,返回值是有意义的,因为 id 可能不匹配,但另一个字段可能已经匹配。
-
const { id, slug, username, userId } = params;1. 运行查询时至少提供id、slug、username、userId变量之一(其余变量未定义/为空)。