I have following prisma.schema:
model Tag {
id Int @id @default(autoincrement())
name String @unique
files FileTag[]
}
model FileTag {
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
tagId Int
file File @relation(fields: [fileId], references: [id], onDelete: Cascade)
fileId Int
@@id([fileId, tagId])
}
Here is my code to update database:
for (const tagId of tagIds){
const tag = await Tags.addFileToTag(parseInt(tagId), fileId);
};
async addFileToTag(tagId: number, fileId: number) {
const client = await getDbClient();
return await client.tag.update({
where: {
id: tagId,
},
data: {
files: {
create: {
fileId
}
}
}
})
}
My goal is reached by this implementation. But the problem is, I don't like this implementation. I am using a loop and calling same update query repeatedly.
Now, I am wondering is there any alternative procedure, (i.e change prisma update to updateMany query) by removing the loop... that will do the same change on database?
updateMany is used to update the same data in many rows but in your case, you want to update different data, so updateMany won't be useful here.
Optionally you could use transactions if atomicity is required and there is a need to make sure that either all tags are updated or if there is any error then no tags gets updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With