Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
RajibTheKing Avatar asked Jan 27 '26 07:01

RajibTheKing


1 Answers

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.

like image 53
Nurul Sundarani Avatar answered Jan 30 '26 12:01

Nurul Sundarani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!