Prisma 中文文档 下载 App

CRUD 基础:findMany、create、update、delete 速查

查询:findMany / findFirst / findUnique

findMany — 查询多条

const allUsers = await prisma.user.findMany()

// 带筛选
const activeUsers = await prisma.user.findMany({
  where: { active: true },
})

// 带排序、分页
const page2 = await prisma.user.findMany({
  orderBy: { createdAt: 'desc' },
  skip: 10,
  take: 10,
})

// 带选择字段(只取需要的字段)
const emails = await prisma.user.findMany({
  select: { email: true },
})
// 返回 [{ email: 'a@b.com' }, ...]

findFirst — 查第一条

const firstActive = await prisma.user.findFirst({
  where: { active: true },
  orderBy: { createdAt: 'desc' },
})
// 返回单个对象或 null

findUnique — 按唯一字段查

const user = await prisma.user.findUnique({
  where: { id: 1 },
})

// 也可以用 @unique 字段
const userByEmail = await prisma.user.findUnique({
  where: { email: 'alice@prisma.io' },
})

findUnique 比 findFirst 快,因为它知道数据库用的是唯一索引。注意:复合唯一键的写法是 where: { id_email: { id: 1, email: 'a@b.com' } }。

错误处理

创建:create / createMany

create — 创建单条

const user = await prisma.user.create({
  data: {
    email: 'alice@prisma.io',
    name: 'Alice',
  },
})

createMany — 批量创建

await prisma.user.createMany({
  data: [
    { email: 'a@prisma.io', name: 'A' },
    { email: 'b@prisma.io', name: 'B' },
  ],
  skipDuplicates: true,  // 遇到唯一冲突跳过不报错
})
// 返回 { count: 2 }

注意:MongoDB 不支持 createMany(它有 insertMany 但 Prisma Client 不暴露)。

更新:update / updateMany / upsert

update — 更新单条

const updated = await prisma.user.update({
  where: { id: 1 },
  data: { name: 'Alice Smith' },
})

找不到记录时抛 P2025。

updateMany — 批量更新

await prisma.user.updateMany({
  where: { role: 'USER' },
  data: { role: 'MODERATOR' },
})
// 返回 { count: N }

upsert — 不存在就创建,存在就更新

const user = await prisma.user.upsert({
  where: { email: 'alice@prisma.io' },
  create: { email: 'alice@prisma.io', name: 'Alice' },
  update: { name: 'Alice Updated' },
})

删除:delete / deleteMany

delete — 删除单条

const deleted = await prisma.user.delete({
  where: { id: 1 },
})

找不到抛 P2025。

deleteMany — 批量删除

await prisma.user.deleteMany({
  where: { inactive: true },
})
// 返回 { count: N }

防误删

deleteMany() 不带 where 会删全表——这通常是个 bug。Prisma Client 会强制你显式写 where: {} 才允许全表删除。

计数与聚合

count — 计数

const total = await prisma.user.count()

// 带筛选
const activeCount = await prisma.user.count({
  where: { active: true },
})

aggregate — 聚合函数

const stats = await prisma.order.aggregate({
  _sum: { totalAmount: true },
  _avg: { totalAmount: true },
  _count: { id: true },
})
// { _sum: { totalAmount: 5000 }, _avg: { totalAmount: 250 }, _count: { id: 20 } }

groupBy — 分组聚合

const byStatus = await prisma.order.groupBy({
  by: ['status'],
  _count: { id: true },
})
// [{ status: 'pending', _count: { id: 5 } }, { status: 'done', _count: { id: 15 } }]