【问题标题】:using prisma, how do you access newly created record from within a nested write (update first, then create within)使用 prisma,如何从嵌套写入中访问新创建的记录(先更新,然后在其中创建)
【发布时间】:2021-04-03 20:16:31
【问题描述】:

使用Prisma,我有一个关于访问从嵌套写入中新创建的记录的问题(先更新,然后在其中创建)。

我正在关注this page in the prisma docs 上的示例。

特别是,我正在查看数据模型中的以下两项:

请注意,为了解决这个问题,我稍微修改了示例,将counter 添加到User

model User {
  id       Int     @id @default(autoincrement())
  email    String  @unique
  posts    Post[]
  counter  Int
}
model Post {
  id         Int      @id @default(autoincrement())
  title      String
  author     User?    @relation(fields:  [authorId], references: [id])
  authorId   Int?
}

现在,假设您想创建一个新的Post 并将其连接到User,同时您还想增加counter

我的假设是,在阅读 this section of the doc 之后,您需要更新现有的 User 并在其中创建一个新的 Post 记录。

const user = await prisma.user.update({
  where: { email: 'alice@prisma.io' },
  data: {
    // increment the counter for this User
    counter: {
      increment: 1,
    },
    // create the new Post for this User
    posts: {
      create: { title: 'Hello World' },
    },
  },
})

我的问题是这样的。上述场景中,如何在查询返回中访问新创建的Post

特别是说你想得到id的新Post

据我所知,返回的 user 对象可能包含所有关联的 Posts 的数组,即如果您将其添加到 update 查询中...

include: {
  posts: true,
}

但我还不知道如何使用 Prisma 获得您刚刚创建的个人 Post 作为此 update 查询的一部分。

【问题讨论】:

    标签: javascript prisma


    【解决方案1】:

    我找到了一种可行的方法。

    它使用the tranaction api

    基本上,不是尝试使用以User 上的更新开始并包含Post 上的嵌套创建的嵌套写入...

    我将这两个操作拆分为单独的变量,并使用prisma.$transaction() 将它们一起运行,如下所示。

    const updateUser = prisma.user.update({
      where: { email: 'alice@prisma.io' },
      data: {
        // increment the counter for this User
        counter: {
          increment: 1,
        },
      },
    });
    
    const createPost = prisma.post.create({
      data: {
        // create the new Post for this User
        title: 'Hello World',
        author: {
          connect: {
            email: 'alice@prisma.io',
          },
        },
      },
    });
    
    const [ updateUserResult, createPostResult ] = await prisma.$transaction([updateUser, createPost ]);
    
    // if createPostResult, then can access details of the new post from here...
    

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2020-12-22
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      相关资源
      最近更新 更多