javascript - 使用 prisma,如何从嵌套写入中访问新创建的记录(先更新,然后在其中创建)

标签 javascript prisma

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

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

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

请注意,为了解决这个问题,我通过向 User 添加一个 counter 稍微修改了示例。

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,同时您还想增加 计数器

我的假设,阅读后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

特别是,假设您想获取新Postid

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

include: {
  posts: true,
}

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

最佳答案

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

它使用 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...

关于javascript - 使用 prisma,如何从嵌套写入中访问新创建的记录(先更新,然后在其中创建),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65454232/

相关文章:

prisma - 我如何利用 Prisma 的隐式关系来创建以下关系? (一对多、多对多、一对一)

javascript - HTML/JS 良好实践 : Is it good to add too many ids?

javascript - 'true' 和 'false' 和 'null' 是什么?

javascript - JavaScript 中数组是如何实现的?那些好的旧 list 怎么了?

javascript - jqGrid - 内联编辑 - 想要更改更改金额值的总计

javascript - 遍历 DOM 时有多少开销?

file-upload - 在 graphql 中处理文件上传的最佳方法是什么?

javascript - Prisma Connection WhereInput 用于枚举值数组?

graphql - 为什么在后端环境中使用 Prisma?

postgresql - Postgres NestJS Prisma 迁移 - 数据库错误代码 : 23502 column of relation contains null values