計算欄位
計算欄位允許您根據現有資料衍生新欄位。常見的範例是當您想要計算全名時。在您的資料庫中,您可能只儲存了名字和姓氏,但您可以定義一個函數,透過組合名字和姓氏來計算全名。計算欄位是唯讀的,並儲存在您應用程式的記憶體中,而不是在您的資料庫中。
使用 Prisma Client 擴充功能
以下範例說明如何建立一個 Prisma Client 擴充功能,在執行時將 fullName
計算欄位新增到 Prisma schema 中的 User
模型。
- Prisma Client 擴充功能
- Prisma schema
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient().$extends({
result: {
user: {
fullName: {
needs: { firstName: true, lastName: true },
compute(user) {
return `${user.firstName} ${user.lastName}`
},
},
},
},
})
async function main() {
/**
* Example query containing the `fullName` computed field in the response
*/
const user = await prisma.user.findFirst()
}
main()
顯示CLI結果
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
firstName String
lastName String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(true)
content String?
authorId Int?
author User? @relation(fields: [authorId], references: [id])
}
計算欄位是類型安全的,並且可以從串連的值到複雜的物件或函數,返回任何內容,這些函數可以作為您模型的實例方法。
Prisma ORM 4.16.0 之前的說明
警告
隨著 Prisma Client 擴充功能自 Prisma ORM 4.16.0 版本起正式發布,不建議使用以下步驟。請使用用戶端擴充功能來完成此操作。
Prisma Client 尚未原生支援計算欄位,但是,您可以定義一個函數,該函數接受泛型類型作為輸入,然後擴充該泛型以確保它符合特定結構。最後,您可以傳回具有額外計算欄位的泛型。讓我們看看它會是什麼樣子
- TypeScript
- JavaScript
// Define a type that needs a first and last name
type FirstLastName = {
firstName: string
lastName: string
}
// Extend the T generic with the fullName attribute
type WithFullName<T> = T & {
fullName: string
}
// Take objects that satisfy FirstLastName and computes a full name
function computeFullName<User extends FirstLastName>(
user: User
): WithFullName<User> {
return {
...user,
fullName: user.firstName + ' ' + user.lastName,
}
}
async function main() {
const user = await prisma.user.findUnique({ where: 1 })
const userWithFullName = computeFullName(user)
}
function computeFullName(user) {
return {
...user,
fullName: user.firstName + ' ' + user.lastName,
}
}
async function main() {
const user = await prisma.user.findUnique({ where: 1 })
const userWithFullName = computeFullName(user)
}
在上面的 TypeScript 範例中,已定義一個 User
泛型,它擴充了 FirstLastName
類型。這表示您傳遞到 computeFullName
的任何內容都必須包含 firstName
和 lastName
鍵。
還定義了 WithFullName<User>
回傳類型,它接受任何 User
並附加一個 fullName
字串屬性。
透過此函數,任何包含 firstName
和 lastName
鍵的物件都可以計算 fullName
。非常棒,對吧?
更進一步
- 了解如何使用 Prisma Client 擴充功能 將計算欄位新增到您的 schema — 範例。
- 了解如何將
computeFullName
函數移動到 自訂模型 中。 - 有一個 開放功能請求 以將原生支援新增到 Prisma Client。如果您希望看到這種情況發生,請務必為該問題投贊成票並分享您的使用案例!