I'm trying to do the following using Prisma:
If a category row with the same hash and user_id I have exists, just update it's "name" field, otherwise, create the row
Is this possible? TS is giving me an error saying that the type of the key given on "where" has to be of categoriesWhereUniqueInput
, yet neither hash nor user_id are unique, they can repeat, it's the combination between the two that's gonna be unique
How can I work around this? Do I have to manually check if there's an id and update/create based on that?
Thanks a lot in advance!
const category = await prisma.categories.upsert({
where: {
hash,
user_id: id,
},
update: {
name,
},
create: {
hash,
name,
user_id: id,
},
});
CodePudding user response:
When a combination of fields is unique, Prisma will generate a new type for the where
condition which is basically just the name of all the relevant fields appended together with _
.
Take a look at the categoriesWhereUniqueInput
to see what the name is. Most likely it is called user_id_hash
or hash_user_id
.
This is what the query will look like, roughly speaking:
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,
},
})