Next js with Prisma:基于两个条件的更新插入
Next js with Prisma: Upsert based on two conditions
我正在尝试使用 Prisma 执行以下操作:
如果具有相同散列的类别行和 user_id 我已经存在,只需更新它的“名称”字段,否则,创建行
这可能吗? TS 给我一个错误,说“where”上给出的键的类型必须是 categoriesWhereUniqueInput
,但 hash 和 user_id 都不是唯一的,它们可以重复,它是两者之间的组合那将是独一无二的
我该如何解决这个问题?我是否必须手动检查是否有 id 和 update/create 基于它?
非常感谢!
const category = await prisma.categories.upsert({
where: {
hash,
user_id: id,
},
update: {
name,
},
create: {
hash,
name,
user_id: id,
},
});
当字段组合是唯一的时,Prisma 将为 where
条件生成一个新类型,它基本上只是所有相关字段的名称加上 _
.
看看 categoriesWhereUniqueInput
看看名字是什么。它很可能被称为 user_id_hash
或 hash_user_id
。
这就是查询的样子,粗略地说:
const category = await prisma.categories.upsert({
where: {
user_id_hash: { // user_id_hash is the type generated by Prisma. Might be called something else though.
user_id: 1,
hash: "foo"
}
},
update: {
name: "bar",
},
create: {
hash: "foo",
name: "bar",
user_id: 1,
},
})
我正在尝试使用 Prisma 执行以下操作:
如果具有相同散列的类别行和 user_id 我已经存在,只需更新它的“名称”字段,否则,创建行
这可能吗? TS 给我一个错误,说“where”上给出的键的类型必须是 categoriesWhereUniqueInput
,但 hash 和 user_id 都不是唯一的,它们可以重复,它是两者之间的组合那将是独一无二的
我该如何解决这个问题?我是否必须手动检查是否有 id 和 update/create 基于它?
非常感谢!
const category = await prisma.categories.upsert({
where: {
hash,
user_id: id,
},
update: {
name,
},
create: {
hash,
name,
user_id: id,
},
});
当字段组合是唯一的时,Prisma 将为 where
条件生成一个新类型,它基本上只是所有相关字段的名称加上 _
.
看看 categoriesWhereUniqueInput
看看名字是什么。它很可能被称为 user_id_hash
或 hash_user_id
。
这就是查询的样子,粗略地说:
const category = await prisma.categories.upsert({
where: {
user_id_hash: { // user_id_hash is the type generated by Prisma. Might be called something else though.
user_id: 1,
hash: "foo"
}
},
update: {
name: "bar",
},
create: {
hash: "foo",
name: "bar",
user_id: 1,
},
})