Prisma:模型查询方法

  • findUnique

    • 使用唯一条件来获取单个数据记录,如根据id查询

    • 支持关键字:where, select, include

    • const result = await prisma.user.findUnique({
        where: {
          email: 'alice@prisma.io',
        },
      })
      
  • findFirst

    • 返回第一个匹配条件的记录

    • 支持关键字:select, include, rejectOnNotFound, where, orderBy, cursor, take, skip, distinct

    • // 获取 title 字段以 A test 开头的第一个 Post 记录,并反转列表(take)
      async function main() {
        const a = await prisma.post.create({
          data: {
            title: 'A test 1',
          },
        })
      
        const b = await prisma.post.create({
          data: {
            title: 'A test 2',
          },
        })
      
        const c = await prisma.post.findFirst({
          where: {
            title: {
              startsWith: 'A test',
            },
          },
          orderBy: {
            title: 'asc',
          },
          take: -1, // 反转列表
        })
      }
      
  • findMany

    • 返回多条记录

    • 支持关键字:select, include, where, orderBy, cursor, take, skip, distinct

    • const user = await prisma.user.findMany({
        where: { name: 'Alice' },
      })
      
  • create

    • 创建一条新的数据库记录

    • 支持关键字:data, select, include

    • Prisma Client 当前不支持在数据库级别批量插入,可手动通过循环实现

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

    • 更新数据

    • 支持关键字:data, where, select, include

    • const user = await prisma.user.update({
        where: { id: 1 },
        data: { email: 'alice@prisma.io' },
      })
      
  • upsert

    • 更新现有、或创建新的数据库记录

    • 支持关键字:create, update, where, select, include

    • // 更新(如果存在)或创建一条 email 为 alice@prisma.io 的 User 记录
      const user = await prisma.user.upsert({
        where: { id: 1 },
        update: { email: 'alice@prisma.io' },
        create: { email: 'alice@prisma.io' },
      })
      
  • delete

    • 删除现有的数据库记录

    • 只支持根据id,或者unique属性进行删除

    • 支持关键字:where, select, include

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

    • 删除多条记录,可根据筛选条件批量删除

    • 支持关键字:where

    • // 删除所有 name 为 Alice 的 User 记录
      const deletedUserCount = await prisma.user.deleteMany({
        where: { name: 'Alice' },
      })
      
      // 删除所有User
      const deletedUserCount = await prisma.user.deleteMany({})
      
  • createMany

    • 在一个事务中创建多个记录,并返回成功插入数

    • 支持关键字:data, skipDuplicates

    • const users = await prisma.user.createMany({
        data: [
          { name: 'Sonali', email: 'sonali@prisma.io' },
          { name: 'Alex', email: 'alex@prisma.io' },
        ],
      })
      
  • updateMany

    • 更新一批已存在的数据库记录,并返回更新的记录数

    • 支持关键字:data, where

    • const updatedUserCount = await prisma.user.updateMany({
        where: { name: 'Alice' },
        data: { name: 'ALICE' },
      })
      
  • count

    • 返回符合条件的数据计数

    • 支持关键字:where, cursor, skip, take, orderBy, distinct, select

    • // 查询所有记录总数、查询name字段非空的总数,查询city字段非空的总数
      const c = await prisma.user.count({
        select: {
          _all: true,
          city: true,
          name: true,
        },
      })
      
  • aggregate

    • 支持关键字:where, orderBy, cursor, skip, take, distinct, _count, _avg, _sum, _min, _ max

    • // 返回所有User记录的profileViews的_min、_max和_count
      const minMaxAge = await prisma.user.aggregata({
          _count: {
          _all: true,
      },
          _max: {
          profileViews: true,
      },
          _min: {
          profileViews: true,
      }
      })
      
      // return : {
      //  _count: { _all: 29 },
      //  _max: { profileViews: 90 },
      //  _min: { profileViews: 0 }
      //}
      
  • groupBy

    • 聚合操作

    • 支持关键字:where, orderBy, by, having, skip, take, _count, _avg, _sum, _min, _max

    • // 按平均 profileViews 大于 200 的 country/city 分组,并返回每组 profileViews 的 _sum
      const groupUsers = await prisma.user.groupBy({
        by: ['country', 'city'],
        _count: {
          _all: true,
          city: true,
        },
        _sum: {
          profileViews: true,
        },
        orderBy: {
          country: 'desc',
        },
        having: {
          profileViews: {
            _avg: {
              gt: 200,
            },
          },
        },
      })
      
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,我可以帮你回答这个问题。 首先,你需要安装并配置好 Prisma。然后,你可以使用以下命令来创建一个新的 Prisma 数据模型: ``` prisma init ``` 这将创建一个新的 Prisma 项目,并在其中包含一个 `datamodel.prisma` 文件。你需要在这个文件中定义 Conduit 应用程序的数据模型。 以下是一个示例数据模型,其中包含了 Conduit 应用程序中的一些基本实体和关系: ``` // datamodel.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } model User { id Int @id @default(autoincrement()) username String @unique email String @unique password String bio String? image String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt follows User[] @relation("Follow", references: [id]) followers User[] @relation("Follow", references: [id]) articles Article[] comments Comment[] } model Article { id Int @id @default(autoincrement()) slug String @unique title String description String body String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt author User @relation("Author", fields: [authorId], references: [id]) authorId Int favorites User[] @relation("Favorite", references: [id]) comments Comment[] } model Comment { id Int @id @default(autoincrement()) body String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt author User @relation(fields: [authorId], references: [id]) authorId Int article Article @relation(fields: [articleId], references: [id]) articleId Int } ``` 在这个数据模型中,我们定义了三个实体:User、Article 和 Comment。每个实体都有一些属性和关系。 例如,User 实体具有 username、email、password、bio、image、createdAt 和 updatedAt 属性。它还有一个 follows 和 followers 关系,用于表示用户之间的关注关系。User 实体还具有 articles 和 comments 关系,用于表示用户发表的文章和评论。 Article 实体具有 slug、title、description、body、createdAt 和 updatedAt 属性。它还有一个 author 关系,表示文章的作者。Article 实体还具有 favorites 和 comments 关系,用于表示用户喜欢的文章和文章的评论。 Comment 实体具有 body、createdAt 和 updatedAt 属性。它还有一个 author 和 article 关系,表示评论的作者和所属文章。 你可以根据自己的需求来定义数据模型,并使用 Prisma 自动创建数据库表和关系。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

川涂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值