排除欄位
預設情況下,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(當查詢中提供 omit
選項時)僅適用於定義它的查詢,而全域 omit 適用於使用相同 Prisma Client 實例進行的每個查詢,除非使用特定選取或覆寫 omit。