适用人群:Node.js/TypeScript开发者
难度:中等
预计学习时间:10-15小时
什么是 Prisma?
Prisma 是 Node.js 和 TypeScript 生态中最流行的 ORM,通过声明式 Schema 定义数据库模型,自动生成类型安全的查询客户端。
| 特性 | 说明 |
|---|---|
| Schema优先 | 用 .prisma 文件定义数据模型 |
| 类型安全 | 自动生成 TypeScript 类型 |
| 自动迁移 | prisma migrate 自动生成 SQL |
| 多数据库 | PostgreSQL/MySQL/SQLite/SQL Server/MongoDB |
| Prisma Studio | 图形化数据管理工具 |
核心用法
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
name String?
avatar String?
posts Post[]
profile Profile?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Profile {
id String @id @default(cuid())
bio String?
userId String @unique
user User @relation(fields: [userId], references: [id])
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
tags Tag[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([authorId])
}
model Tag {
id String @id @default(cuid())
name String @unique
posts Post[]
}
// 使用 Prisma Client
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// 创建
const user = await prisma.user.create({
data: {
email: 'alice@example.com',
name: 'Alice',
profile: { create: { bio: 'Hello!' } },
posts: {
create: [
{ title: '第一篇文章', content: '内容...' },
{ title: '第二篇文章', published: true }
]
}
},
include: { profile: true, posts: true }
})
// 查询
const posts = await prisma.post.findMany({
where: {
published: true,
author: { name: { contains: 'Alice' } }
},
include: { author: true, tags: true },
orderBy: { createdAt: 'desc' },
take: 10,
skip: 0
})
// 更新
const updated = await prisma.post.update({
where: { id: 'post-id' },
data: { published: true },
include: { author: true }
})
// 删除
await prisma.post.delete({ where: { id: 'post-id' } })
// 聚合
const stats = await prisma.post.aggregate({
_count: true,
_avg: { id: true },
where: { published: true }
})
// 事务
const [user, profile] = await prisma.$transaction([
prisma.user.create({ data: { email: 'bob@test.com', name: 'Bob' } }),
prisma.profile.create({ data: { bio: 'Hi!', userId: 'xxx' } })
])
// 原生SQL
const results = await prisma.$queryRaw`
SELECT u.name, COUNT(p.id) as post_count
FROM "User" u
LEFT JOIN "Post" p ON u.id = p."authorId"
GROUP BY u.name
ORDER BY post_count DESC
`
# 常用命令
npx prisma init # 初始化
npx prisma db push # 推送Schema到数据库
npx prisma migrate dev --name init # 创建迁移
npx prisma generate # 生成客户端
npx prisma studio # 打开图形化工具
npx prisma db seed # 执行种子数据
与其他ORM对比
| ORM | 语言 | 类型安全 | 学习曲线 | 生态 |
|---|---|---|---|---|
| Prisma | TS/JS | 极好 | 中等 | 最大 |
| Drizzle | TS/JS | 极好 | 低 | 增长中 |
| TypeORM | TS/JS | 好 | 中等 | 成熟 |
| Sequelize | JS | 一般 | 中等 | 成熟 |
| Eloquent | PHP | 好 | 低 | 最大(PHP) |
推荐资源
| 赐源 | 说明 |
|---|---|
| Prisma官方文档 | 最好的学习资料 |
| Prisma Examples | 官方示例集 |
| Prisma Data Platform | 数据库管理和浏览 |