第11周:Prisma!
发布: (2025年12月17日 GMT+8 12:57)
4 min read
原文: Dev.to
Source: Dev.to
Topics Covered✅
- 理解 ORM 实际解决了什么
- 使用 Prisma 定义数据库模式
- 生成类型安全的数据库客户端
- 干净且安全地执行 CRUD 操作
1. What is Prisma and why do we need it? 🧠
Prisma 是一个 ORM(对象关系映射器),它在数据库和应用代码之间充当桥梁。
Without Prisma
SELECT * FROM users WHERE email = 'test@gmail.com';
With Prisma
const user = await prisma.user.findUnique({
where: { email: "test@gmail.com" }
});
Why this matters
- 不需要为每个操作编写原始 SQL
- 查询变得 类型安全
- 重构数据库字段不会悄悄导致错误
- 自动补全 + 编译时检查防止运行时 bug
2. Prisma Schema — the single source of truth 📄
首先,在项目中初始化 Prisma(参见官方文档)。
schema.prisma 文件定义了:
- 数据库连接
- 模型(表)
- 模型之间的关系
Basic example
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
}
- 创建一个
User表 - 对
email强制唯一性 - 生成编辑器能够识别的类型
Generate the client:
npx prisma generate
Using the generated client
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from "@/app/generated/prisma/client";
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
});
const prisma = new PrismaClient({ adapter });
3. Migrations — evolving the database safely 🔁
数据库会随时间变化。Prisma 通过 迁移 处理模式变更。
npx prisma migrate dev --name add-user-model
它的作用:
- 创建迁移文件
- 将更改应用到数据库
- 保留模式演进的历史记录
迁移可以保持本地、预发布和生产数据库同步,生成的文件包含每次更改的原始 SQL。
4. CRUD operations with Prisma ✍️
Create
await prisma.user.create({
data: {
email: "nikhil@gmail.com",
name: "Nikhil"
}
});
Read
const users = await prisma.user.findMany();
Update
await prisma.user.update({
where: { id: 1 },
data: { name: "Updated Name" }
});
Delete
await prisma.user.delete({
where: { id: 1 }
});
所有操作都是:
- 有类型的
- 编译时已验证
- 行为可预测
完整参数细节请参考 Prisma 文档。
5. Relations and foreign keys made simple 🔗
在 Prisma 中定义关系既简洁又具表达力。
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
user User @relation(fields: [userId], references: [id])
userId Int
}
Prisma 现在能够理解:
- 一个用户 → 多个帖子
- 如何在内部进行关联查询
- 如何安全地获取嵌套数据
Fetching related data
const user = await prisma.user.findUnique({
where: { id: 1 },
include: { posts: true }
});
6. New things I learned this week 🔄
- Prisma 充当代码与数据库之间的中介,提供的类型安全显著降低了 bug。
- 以模式为先的设计可以防止整类运行时错误。
Wrapping up
Prisma 可能看起来像“又一个工具”,但它从根本上改变了我们与数据库交互的信心。干净的模式和安全的迁移让生产系统更加可靠。
如果你有任何问题或反馈,欢迎留言!如果你有项目想法,也可以在评论区告诉我。
我下周会再来分享。期间,保持坚持!