跳到主要内容

排除字段

默认情况下,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 选项添加多个键值对。使用与之前相同的 schema,您可以使用以下方式忽略 password 和 email

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

何时全局或局部使用 omit

理解何时全局或局部忽略一个字段很重要

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

局部 omit(当在查询中提供了 omit 选项时)仅应用于定义它的查询,而全局 omit 应用于使用相同 Prisma Client 实例执行的每个查询,除非使用了特定的 select 或覆盖了 omit