findFirst 查询在棱镜 2 中显示不相关的数据



我想查询一个带有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}

我的查询有问题吗?

镜柱模型

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?
}

将查询筛选器嵌套在 OR 子句中。

const { id, slug, username, userId  } = params;
const posts = await prisma.post.findFirst({
where: {
OR: [
{ id },
{ slug },
{ author: { profile: { username } } },
{ authorId: userId }
]
}
});

问题

根据您在评论中提供的解释,您希望:

查询具有id, slug, username, userId的帖子,其中一个或多个可能为空或未定义单个查询。如果字段为 null/未定义,则应忽略特定查询的该字段。

溶液

在我开始解决方案之前,您需要知道nullundefined在Prisma中具有特殊意义。

  • null是一个值
  • undefined意味着什么都不做

所以基本上,如果你为任何字段提供 undefined,它就会被有效地忽略。有关此内容的更多信息,请单击此处

知道了这些信息,您需要将参数参数中的null值转换为undefined,因为您只想忽略该特定查询中的字段。您可以按如下方式设置查询:


async function foo(params) {
const { id, slug, username, userId } = params;
const post = await prisma.post.findFirst({
where: {
id: id ? id : undefined,
slug: slug ? slug : undefined,
authorId: userId ? userId : undefined,
author: username
? {
profile: {
username: username,
},
}
: undefined,
},
});
}

最新更新