计算字段
计算字段允许您基于现有数据派生新字段。一个常见的例子是当您想要计算全名时。在您的数据库中,您可能只存储名字和姓氏,但您可以定义一个函数,通过组合名字和姓氏来计算全名。计算字段是只读的,并存储在应用程序的内存中,而不是在您的数据库中。
使用 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 添加原生支持。如果您希望看到这种情况发生,请务必为该问题投票并分享您的用例!