`model`:将自定义方法添加到你的模型中
Prisma 客户端扩展从版本 4.16.0 及更高版本开始正式可用。它们是在 4.7.0 版本的预览版中引入的。如果你运行的版本早于 4.16.0,请确保启用 clientExtensions
Preview 功能标志。
¥Prisma Client extensions are Generally Available from versions 4.16.0 and later. They were introduced in Preview in version 4.7.0. Make sure you enable the clientExtensions
Preview feature flag if you are running on a version earlier than 4.16.0.
你可以使用 model
Prisma 客户端扩展 组件类型向模型添加自定义方法。
¥You can use the model
Prisma Client extensions component type to add custom methods to your models.
model
组件的可能用途包括:
¥Possible uses for the model
component include the following:
-
新业务将与现有 Prisma 客户端业务一起运营,例如
findMany
¥New operations to operate alongside existing Prisma Client operations, such as
findMany
-
封装业务逻辑
¥Encapsulated business logic
-
重复操作
¥Repetitive operations
-
特定于模型的实用程序
¥Model-specific utilities
添加自定义方法
¥Add a custom method
使用 $extends
客户级方法 创建扩展客户端。扩展客户端是标准 Prisma 客户端的一种变体,由一个或多个扩展封装。使用 model
扩展组件向架构中的模型添加方法。
¥Use the $extends
client-level method to create an extended client. An extended client is a variant of the standard Prisma Client that is wrapped by one or more extensions. Use the model
extension component to add methods to models in your schema.
将自定义方法添加到特定模型
¥Add a custom method to a specific model
要扩展架构中的特定模型,请使用以下结构。此示例向 user
模型添加一个方法。
¥To extend a specific model in your schema, use the following structure. This example adds a method to the user
model.
const prisma = new PrismaClient().$extends({
name?: '<name>', // (optional) names the extension for error logs
model?: {
user: { ... } // in this case, we extend the `user` model
},
});
示例
¥Example
以下示例将名为 signUp
的方法添加到 user
模型中。此方法使用指定的电子邮件地址创建一个新用户:
¥The following example adds a method called signUp
to the user
model. This method creates a new user with the specified email address:
const prisma = new PrismaClient().$extends({
model: {
user: {
async signUp(email: string) {
await prisma.user.create({ data: { email } })
},
},
},
})
你可以在应用中调用 signUp
,如下所示:
¥You would call signUp
in your application as follows:
const user = await prisma.user.signUp('john@prisma.io')
向架构中的所有模型添加自定义方法
¥Add a custom method to all models in your schema
要扩展架构中的所有模型,请使用以下结构:
¥To extend all models in your schema, use the following structure:
const prisma = new PrismaClient().$extends({
name?: '<name>', // `name` is an optional field that you can use to name the extension for error logs
model?: {
$allModels: { ... }
},
})
示例
¥Example
以下示例向所有模型添加 exists
方法。
¥The following example adds an exists
method to all models.
const prisma = new PrismaClient().$extends({
model: {
$allModels: {
async exists<T>(
this: T,
where: Prisma.Args<T, 'findFirst'>['where']
): Promise<boolean> {
// Get the current model at runtime
const context = Prisma.getExtensionContext(this)
const result = await (context as any).findFirst({ where })
return result !== null
},
},
},
})
你可以在应用中调用 exists
,如下所示:
¥You would call exists
in your application as follows:
// `exists` method available on all models
await prisma.user.exists({ name: 'Alice' })
await prisma.post.exists({
OR: [{ title: { contains: 'Prisma' } }, { content: { contains: 'Prisma' } }],
})
从另一个自定义方法调用一个自定义方法
¥Call a custom method from another custom method
如果两个方法是在同一模型上声明的,则可以从另一个自定义方法调用这两个方法。例如,你可以从 user
模型上的另一个自定义方法调用 user
模型上的自定义方法。这两个方法是在同一扩展中还是在不同扩展中声明并不重要。
¥You can call a custom method from another custom method, if the two methods are declared on the same model. For example, you can call a custom method on the user
model from another custom method on the user
model. It does not matter if the two methods are declared in the same extension or in different extensions.
为此,请使用 Prisma.getExtensionContext(this).methodName
。请注意,你不能使用 prisma.user.methodName
。这是因为 prisma
尚未扩展,因此不包含新方法。
¥To do so, use Prisma.getExtensionContext(this).methodName
. Note that you cannot use prisma.user.methodName
. This is because prisma
is not extended yet, and therefore does not contain the new method.
例如:
¥For example:
const prisma = new PrismaClient().$extends({
model: {
user: {
firstMethod() {
...
},
secondMethod() {
Prisma.getExtensionContext(this).firstMethod()
}
}
}
})
运行时获取当前模型名称
¥Get the current model name at runtime
该功能从 4.9.0 版本开始可用。
¥This feature is available from version 4.9.0.
你可以在运行时使用 Prisma.getExtensionContext(this).$name
获取当前模型的名称。你可以使用它将模型名称写入日志、将名称发送到另一个服务或根据模型对代码进行分支。
¥You can get the name of the current model at runtime with Prisma.getExtensionContext(this).$name
. You might use this to write out the model name to a log, to send the name to another service, or to branch your code based on the model.
例如:
¥For example:
// `context` refers to the current model
const context = Prisma.getExtensionContext(this)
// `context.name` returns the name of the current model
console.log(context.name)
// Usage
await(context as any).findFirst({ args })
有关在运行时检索当前模型名称的具体示例,请参阅 向架构中的所有模型添加自定义方法。
¥Refer to Add a custom method to all models in your schema for a concrete example for retrieving the current model name at runtime.
高级类型安全性:用于定义通用扩展的类型实用程序
¥Advanced type safety: type utilities for defining generic extensions
你可以使用 类型实用程序 提高共享扩展中 model
组件的类型安全性。
¥You can improve the type-safety of model
components in your shared extensions with type utilities.