【发布时间】:2021-09-17 22:50:40
【问题描述】:
我正在尝试更新 Prisma 中的一对多关系。我的架构看起来像这样
model A_User {
id Int @id
username String
age Int
bio String @db.VarChar(1000)
createdOn DateTime @default(now())
features A_Features[]
}
model A_Features {
id Int @id @default(autoincrement())
description String
A_User A_User? @relation(fields: [a_UserId], references: [id])
a_UserId Int?
}
我正在尝试向 id: 1 的用户添加一些新功能,或者如果它们已经存在则更新它们。
我正在尝试做类似的事情
const post = await prisma.a_User.update({
where: { id: 1},
data: {
features: {
upsert: [
{ description: 'first feature'},
{ description: 'second feature'}
]
}
}
})
编译器不高兴,它告诉我
Type '{ features: { upsert: { description: string; }[]; }; }' is not assignable to type '(Without<A_UserUpdateInput, A_UserUncheckedUpdateInput> & A_UserUncheckedUpdateInput) | (Without<...> & A_UserUpdateInput)'.
Object literal may only specify known properties, and 'features' does not exist in type '(Without<A_UserUpdateInput, A_UserUncheckedUpdateInput> & A_UserUncheckedUpdateInput) | (Without<...> & A_UserUpdateInput)'.ts(2322)
index.d.ts(1572, 5): The expected type comes from property 'data' which is declared here on type '{ select?: A_UserSelect; include?: A_UserInclude; data: (Without<A_UserUpdateInput, A_UserUncheckedUpdateInput> & A_UserUncheckedUpdateInput) | (Without<...> & A_UserUpdateInput); where: A_UserWhereUniqueInput; }'
(property) features: {
upsert: {
description: string;
}[];
}
我不知道该怎么做,也无法在文档中找到明确的帮助。关于如何实现它或在哪里可以找到一些示例的任何想法?
【问题讨论】:
-
能否请您澄清“如果它们已经存在则更新它们”的意思。如果它们已经存在于特定
A_User的features关系中,或者它们是否存在于A_Features表中的任何地方?此外,如果您尝试添加的功能之一已经存在,究竟您希望该特定功能如何“更新”? -
我对这个后端的东西很陌生,如果不清楚,请道歉。我认为我需要做的是检查具有该特定描述的功能是否存在,如果不存在,我需要创建它并将其添加给用户,如果确实存在,我只需要添加它给用户。通过“更新”,我想这意味着删除一个功能并在其位置插入另一个功能。你的评论已经让我明白我一直在以错误的方式看待这个问题。谢谢
-
好的,这有帮助。再澄清一点。您是在尝试“附加”还是“覆盖”现有功能。例如,假设
User和id为 1 已经有两个features分别带有description"feature1" 和 "feature2"。现在您在User上运行更新操作,id为 1,提供features:“feature2”和“feature3”。更新后User和id为1 的features的期望最终状态是什么?请记住,在您进行更新操作之前,“feature2”已经存在。 -
在上述情况下,最终状态将是“feature2”和“feature3”(“feature2”不会改变,而“feature1”被“feature3”覆盖)。
-
谢谢,还有一个问题,我可以提供一个具体的解决方案。两个不同的
A_User记录可以在其features中具有完全相同的description字段的A_Features记录吗?换一种说法,带有某个description的A_Features记录对于一个A_User记录是唯一的还是可以连接到许多A_User记录?
标签: mysql typescript prisma