排除字段
默认情况下,Prisma Client 会返回模型中的所有字段。您可以使用 select
来缩小结果集,但如果您的模型很大,而您只想排除少量字段,这种方式可能会很笨拙。
信息
从 Prisma ORM 6.2.0 开始,通过可以传递给 Prisma Client 的 omit
选项支持排除字段。从 5.16.0 到 6.1.0 版本,您必须使用 omitApi
预览功能才能访问此选项。
使用 omit
全局排除字段
以下是类型安全地*全局*排除字段(即针对给定模型的所有查询)的方式
- 代码
- Schema
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 } })
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
firstName String
lastName String
email String @unique
password String
}
使用 omit
局部排除字段
以下是类型安全地*局部*排除字段(即针对单个查询)的方式
- 代码
- Schema
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
}
})
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
firstName String
lastName String
email String @unique
password String
}
如何排除多个字段
排除多个字段与选择多个字段的工作方式相同:将多个键值对添加到 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
来“覆盖”此行为。
- 显式选择
- Omit False
const user = await prisma.user.findUnique({
select: {
firstName: true,
lastName: true,
password: true // The password field is now selected.
},
where: {
id: 1
}
})
const user = await prisma.user.findUnique({
omit: {
password: false // The password field is now selected.
},
where: {
id: 1
}
})
何时使用 omit
全局或局部排除
理解何时全局或局部排除字段非常重要
- 如果您排除字段是为了防止它意外地包含在查询中,最好*全局*排除它。例如:全局排除
User
模型中的password
字段,以防止敏感信息意外泄露。 - 如果您排除字段是因为查询中不需要它,最好*局部*排除它。
局部排除(当查询中提供了 omit
选项时)仅适用于定义它的查询,而全局排除适用于使用同一 Prisma Client 实例进行的每个查询,除非使用了特定的 select 或 omit 被覆盖。