Prisma ORM指南

Schema 定义

// schema.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model User { id Int @id @default(autoincrement()) email String @unique name String? createdAt DateTime @default(now()) posts Post[] profile Profile? } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int tags Tag[] } model Tag { id Int @id @default(autoincrement()) name String @unique posts Post[] }

查询

const prisma = new PrismaClient(); // 查找 const users = await prisma.user.findMany({ where: { email: { contains: '@example.com' } }, orderBy: { createdAt: 'desc' }, take: 10, skip: 0, include: { posts: { where: { published: true } } }, }); // 创建 const user = await prisma.user.create({ data: { email: 'alice@example.com', name: 'Alice', posts: { create: { title: 'First post' } }, }, }); // 更新 await prisma.post.update({ where: { id: 1 }, data: { published: true } }); // 删除 await prisma.user.delete({ where: { id: 1 } }); // 插入或更新 await prisma.user.upsert({ where: { email: 'alice@example.com' }, update: { name: 'Alice Smith' }, create: { email: 'alice@example.com', name: 'Alice Smith' }, });

CLI 命令

命令说明
npx prisma init初始化 Prisma
npx prisma generate生成客户端
npx prisma migrate dev创建并应用迁移
npx prisma migrate deploy生产环境应用迁移
npx prisma db push不创建迁移直接推送Schema
npx prisma studio打开数据库浏览器
npx prisma db seed运行数据填充脚本