跳至主要内容

排除字段

默认情况下,Prisma Client 返回模型中的所有字段。您可以使用 select 来缩小结果集,但如果您的模型很大,而您只想排除少量字段,这可能会很麻烦。

信息

自 Prisma ORM 6.2.0 版本起,Prisma Client 通过 omit 选项支持排除字段。从 5.16.0 到 6.1.0 版本,您必须使用 omitApi 预览功能才能访问此选项。

使用 omit 全局排除字段

以下是全局(即对给定模型的所有查询)排除字段的类型安全方法

const prisma = new PrismaClient({
omit: {
user: {
password: true
}
}
})

// The password field is excluded in all queries, including this one
const user = await prisma.user.findUnique({ where: { id: 1 } })

使用 omit 局部排除字段

以下是局部(即对单个查询)排除字段的类型安全方法

const prisma = new PrismaClient()

// The password field is excluded only in this query
const user = await prisma.user.findUnique({
omit: {
password: true
},
where: {
id: 1
}
})

如何排除多个字段

排除多个字段与选择多个字段的方式相同:向 omit 选项添加多个键值对。使用与之前相同的模式,您可以通过以下方式排除密码和电子邮件

const prisma = new PrismaClient()

// password and email are excluded
const user = await prisma.user.findUnique({
omit: {
email: true,
password: true,
},
where: {
id: 1,
},
})

可以局部和全局排除多个字段。

如何选择之前排除的字段

如果您全局排除某个字段,您可以通过明确选择该字段或在查询中将 omit 设置为 false 来“覆盖”。

const user = await prisma.user.findUnique({
select: {
firstName: true,
lastName: true,
password: true // The password field is now selected.
},
where: {
id: 1
}
})

确保排除的字段不出现在 TypeScript 类型中

虽然 omit 选项正确地从运行时结果中移除了字段,但 TypeScript 有时不会在推断的类型中反映这些排除,特别是当 omit 配置没有严格类型化时。

如果您在单独的变量中定义 omit 配置并且不使用 as const,TypeScript 会将类型推断为 { [key: string]: boolean },这对于 Prisma 来说太宽泛,无法知道哪些字段真正被省略了。这会导致被省略的字段仍然出现在类型系统中,即使它们在运行时不存在。

推荐的修复方法是使用 as const 来确保类型是精确的

const omitConfig = {
profile: { email: true },
user: { password: true },
} as const;

const prisma = new PrismaClient({ omit: omitConfig });

这确保 TypeScript 准确地知道哪些字段被省略,并会在类型中反映出来。

何时全局或局部使用 omit

了解何时全局或局部省略字段很重要

  • 如果您为了防止字段意外地包含在查询中而省略它,最好是全局省略它。例如:全局省略 User 模型中的 password 字段,以防止敏感信息意外暴露。
  • 如果您因为查询中不需要某个字段而省略它,最好是局部省略它。

局部省略(当在查询中提供了 omit 选项时)仅适用于它所定义的查询,而全局省略适用于使用相同 Prisma Client 实例进行的所有查询,除非使用了特定的 select 或 omit 被覆盖

© . This site is unofficial and not affiliated with Prisma Data, Inc.