計算欄位
計算欄位允許您基於現有資料派生新欄位。一個常見的例子是當您想要計算全名時。在您的資料庫中,您可能只儲存名字和姓氏,但您可以定義一個函式,透過組合名字和姓氏來計算全名。計算欄位是隻讀的,儲存在應用程式的記憶體中,而不是資料庫中。
使用 Prisma Client 擴充套件
以下示例展示瞭如何建立Prisma Client 擴充套件,在執行時為 Prisma schema 中的 User 模型新增一個 fullName 計算欄位。
- 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 示例中,定義了一個擴充套件 FirstLastName 型別的 User 泛型。這意味著您傳遞給 computeFullName 的任何內容都必須包含 firstName 和 lastName 鍵。
還定義了一個 WithFullName<User> 返回型別,它接受任何 User 並附加一個 fullName 字串屬性。
有了這個函式,任何包含 firstName 和 lastName 鍵的物件都可以計算 fullName。很酷,對吧?
進一步探索
- 瞭解如何使用 Prisma Client 擴充套件將計算欄位新增到您的 schema — 示例。
- 瞭解如何將
computeFullName函式移動到自定義模型中。 - 有一個開放的功能請求,用於為 Prisma Client 新增原生支援。如果您希望看到它實現,請務必為此 issue 點贊並分享您的用例!