【问题标题】:Create multiple records from nested Prisma transaction?从嵌套的 Prisma 事务中创建多条记录?
【发布时间】:2020-12-22 05:51:33
【问题描述】:

我有以下 Prisma 查询,在用户注册时运行,它创建用户帐户并创建他们将所属的团队。

prisma.account.create({
  data: {
    team: {
      create: { name: team_name },
    },
    username,
    email,
    password
  },
})

但是,用户还需要通过电子邮件验证他们的团队创建。为此,我需要为其创建记录的第三个数据库表,prisma Schema 为:

prisma.team_verification.create({
  data: {
    team: {
      connect: {
        team_id,
      },
    },
  },
})

有什么办法可以合并这两个查询,以便在注册时创建一个新团队,一个带有 team_id = 新团队的新“帐户”,以及一个带有 team_id = 新团队的新“team_verification”团队?

【问题讨论】:

  • 如果可能的话,你能分享你的架构吗?

标签: postgresql prisma


【解决方案1】:

您可以使用交互式事务。 由于这是一个预览功能,您应该在生成器客户端中进行配置。

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["interactiveTransactions"]
}

然后:

const user: User = await prisma.$transaction(async (prisma) => {

   let user= await prisma.account.create({
    data: {
      team: {
        create: { name: team_name },
      },
      username,
      email,
      password
    },
  })
  
  prisma.team_verification.create({
   data: {
    team: {
     connect: { user.id }
    },
   },
 })

  return user

})

【讨论】:

    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多