Prisma
Prisma ORM 是一个开源的数据库工具包,通过提供类型安全的查询构建器和直观的数据建模界面,简化了应用中的数据库访问和管理。
【Prisma ORM is an open-source database toolkit that simplifies database access and management in applications by providing a type-safe query builder and an intuitive data modeling interface.】
在开始之前,请确保你已经安装并配置了 Prisma。更多信息,请参阅 Prisma 文档
【Before getting started, make sure you have Prisma installed and configured. For more information, see Prisma Documentation】
示例用法
【Example Usage】
你可以使用 Prisma 适配器按如下方式连接到你的数据库。
【You can use the Prisma adapter to connect to your database as follows.】
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "sqlite",
}),
});从 Prisma 7 开始,output 路径字段是必需的。如果你在 schema.prisma 文件中配置了自定义输出路径(例如 output = "../src/generated/prisma"),请确保从该位置导入 Prisma 客户端,而不是从 @prisma/client 导入。更多信息请参见 这里。
架构生成与迁移
【Schema generation & migration】
Better Auth CLI 允许你根据你的 Better Auth 配置和插件生成或迁移数据库模式。
【The Better Auth CLI allows you to generate or migrate your database schema based on your Better Auth configuration and plugins.】
Prisma 模式生成 | Prisma 模式迁移 |
|---|---|
| ✅ 支持 | ❌ 不支持 |
npx @better-auth/cli@latest generate联接(实验性)
【Joins (Experimental)】
当 Better-Auth 需要在单个查询中从多张表获取相关数据时,数据库连接(joins)非常有用。像 /get-session、/get-full-organization 等端点以及许多其他端点都极大地受益于这一功能,根据数据库延迟的不同,性能提升可达 2 到 3 倍。
【Database joins is useful when Better-Auth needs to fetch related data from multiple tables in a single query.
Endpoints like /get-session, /get-full-organization and many others benefit greatly from this feature,
seeing upwards of 2x to 3x performance improvements depending on database latency.】
自 1.4.0 版本起,Prisma 适配器原生支持连接(joins)。要启用此功能,你需要在身份验证配置中将 experimental.joins 选项设置为 true。
【The Prisma adapter supports joins out of the box since version 1.4.0.
To enable this feature, you need to set the experimental.joins option to true in your auth configuration.】
export const auth = betterAuth({
experimental: { joins: true }
});请确保你的 Prisma 模式中定义了必要的关系。
如果在 Prisma 模式中未看到任何关系,你可以使用 @relation 指令手动添加它们,
或者运行我们的最新 CLI 版本 npx @better-auth/cli@latest generate 来生成包含关系的新 Prisma 模式。
附加信息
【Additional Information】
- 如果你正在寻找性能改进或技巧,请查看我们的 性能优化指南。
- 如何在 Next.js 中使用 Prisma ORM 和 Better Auth