Skip to content
On this page

Prisma 查询 API

Prisma Client 提供了一套功能强大且直观的查询 API,用于从数据库中读取和过滤数据。

基础查询方法

findUnique

获取具有唯一标识符的单个记录:

typescript
const user = await prisma.user.findUnique({
  where: {
    id: 1,
    // 或者使用其他唯一字段
    // email: 'alice@example.com'
  }
})

findFirst

获取满足条件的第一个记录:

typescript
const user = await prisma.user.findFirst({
  where: {
    email: {
      contains: 'example.com'
    }
  }
})

findMany

获取满足条件的多个记录:

typescript
const users = await prisma.user.findMany({
  where: {
    age: {
      gt: 18
    }
  }
})

过滤操作符

比较操作符

  • equals: 等于
  • in: 包含在数组中
  • notIn: 不包含在数组中
  • lt: 小于
  • lte: 小于等于
  • gt: 大于
  • gte: 大于等于
typescript
const users = await prisma.user.findMany({
  where: {
    age: {
      gte: 18,
      lt: 65
    }
  }
})

字符串操作符

  • contains: 包含
  • startsWith: 以...开头
  • endsWith: 以...结尾
typescript
const users = await prisma.user.findMany({
  where: {
    email: {
      contains: 'gmail',
      mode: 'insensitive'  // 不区分大小写
    }
  }
})

逻辑操作符

  • AND: 逻辑与
  • OR: 逻辑或
  • NOT: 逻辑非
typescript
const users = await prisma.user.findMany({
  where: {
    AND: [
      { age: { gte: 18 } },
      { email: { endsWith: 'gmail.com' } }
    ]
  }
})

排序

typescript
const users = await prisma.user.findMany({
  orderBy: {
    createdAt: 'desc'  // 按创建时间降序排列
  }
})

// 多字段排序
const users = await prisma.user.findMany({
  orderBy: [
    { role: 'asc' },
    { email: 'desc' }
  ]
})

分页

typescript
const users = await prisma.user.findMany({
  skip: 10,    // 跳过前10条
  take: 5      // 获取5条记录
})

选择特定字段

typescript
const users = await prisma.user.findMany({
  select: {
    id: true,
    email: true,
    profile: {
      select: {
        bio: true
      }
    }
  }
})

关系查询

使用 include

typescript
const userWithPosts = await prisma.user.findUnique({
  where: { id: 1 },
  include: {
    posts: {
      where: { published: true },
      orderBy: { createdAt: 'desc' },
      take: 5
    }
  }
})

使用 select

typescript
const userWithPosts = await prisma.user.findUnique({
  where: { id: 1 },
  select: {
    email: true,
    posts: {
      select: {
        title: true,
        published: true
      }
    }
  }
})

聚合查询

计数

typescript
const userCount = await prisma.user.count({
  where: {
    email: {
      contains: 'example.com'
    }
  }
})

平均值、总和、最小值、最大值

typescript
const aggregateResult = await prisma.post.aggregate({
  where: {
    published: true
  },
  _avg: {
    viewCount: true
  },
  _sum: {
    viewCount: true
  },
  _min: {
    createdAt: true
  },
  _max: {
    createdAt: true
  }
})

分组查询

typescript
const groupedUsers = await prisma.user.groupBy({
  by: ['role', 'country'],
  where: {
    age: { gte: 18 }
  },
  _count: {
    _all: true
  },
  _avg: {
    age: true
  }
})

Distinct 查询

typescript
const distinctRoles = await prisma.user.findMany({
  select: {
    role: true
  },
  distinct: ['role']
})

原生查询

对于复杂查询,可以使用原生 SQL:

typescript
const result = await prisma.$queryRaw`
  SELECT u.id, u.name, COUNT(p.id) as post_count
  FROM User u
  LEFT JOIN Post p ON u.id = p.userId
  GROUP BY u.id, u.name
`

性能优化建议

  1. 使用 select 只获取需要的字段
  2. 合理使用索引
  3. 使用 takeskip 进行分页
  4. 避免 N+1 查询问题,使用 include

总结

Prisma 的查询 API 提供了丰富而直观的方法来查询数据库,支持复杂的过滤、排序、分页和聚合操作。