【发布时间】: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