'Update multiple rows using Prisma without manual loops

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nurul Sundarani