概述
Prisma 用 schema 文件定义模型和关系,生成类型安全的客户端,并通过迁移管理数据库结构变化。
核心 API
Prisma Schema:声明式建模语言,定义表、字段和关系。Prisma Client:类型安全的 CRUD 操作,带自动补全和编译期检查。prisma migrate:根据 schema 变化生成并应用数据库迁移。findMany:按过滤、排序和分页查询多条记录。create:插入新记录。
model Order {
id Int @id @default(autoincrement())
customerId Int
total Int
createdAt DateTime @default(now())
@@index([customerId, createdAt])
}
const orders = await prisma.order.findMany({
where: { customerId },
orderBy: { createdAt: 'desc' },
take: 20,
});
使用注意
迁移文件要提交并审查,生产避免 db push。查询要包含租户和授权条件。为高频过滤建索引。连接池与无服务器环境要使用适配方案。
验证方式
对测试数据库应用迁移,断言 CRUD、关系和过滤结果;检查生成的迁移 SQL 与 schema 一致。