我下面有一个工作代码,如果数据不存在则插入数据(但如果存在则不更新)。在下面的实现中,我正在循环upsert
,它工作得很好。
我的问题是,如何获取那些新插入的数据?(排除已经存在的数据)。您知道如何以尽可能短的方式实现这一目标吗?
我做了一些研究,发现了这个可能的 github 解决方案,但我不明白。因为它还返回数据,即使它已经存在。
this.data = await prisma.$transaction(
temp.map((provider) =>
prisma.provider.upsert({
where: {
user_id_api_key: {
user_id: provider.user_id,
api_key: provider.api_key
}
},
create: provider,
update: {}
})
)
)
console.log(this.data) // it still return data even if its already existing
Run Code Online (Sandbox Code Playgroud)
从 GitHub 复制并粘贴解决方案,并对其进行更多解释:
const maybeUserId = 42
const user = await prisma.user.upsert({
create: {
name: "Nikolas",
email: "burk@prisma.io"
},
update: {
name: "Nikolas",
email: "burk@prisma.io",
},
where: {
id: maybeUserId
}
})
if (user.id === maybeUserId) {
console.log(`An existing user was updated`)
} else {
console.log(`A new user was created`)
}
Run Code Online (Sandbox Code Playgroud)
如果您通过 来创建/更新用户id
,您将使用id
来在数据库中更新插入该特定用户。返回的用户要么具有相同的用户id
,这意味着该用户id
已经在数据库中,因此这是一项update
操作,要么该用户不在数据库中,因为已使用新用户id
(由数据库生成)创建了新用户。
替代方案 1:
model User {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
...
}
Run Code Online (Sandbox Code Playgroud)
upsert后,您可以检查createdAt和updatedAt日期是否相同。
替代方案 2:
调整架构中的用户模型:
model User {
...
wasUpdated Boolean @default(false) // false upon create
}
Run Code Online (Sandbox Code Playgroud)
然后将其设置true
为进行编辑并随后检查:
const user = await prisma.user.upsert({
create: {
email,
name,
},
update: {
email,
name,
wasUpdated: true,
},
where: {
email,
},
});
if (user.wasUpdated) {
console.log('Was updated.);
} else {
console.log('Was created.);
}
Run Code Online (Sandbox Code Playgroud)