How to update multiple rows with different data in Prisma
P粉478445671
P粉478445671 2023-12-25 13:03:44
0
1
438

What is the best way to update many records with different data? This is what I did

const updateBody = JSON.parse(req.body);

      try {
        for (let object of updateBody) {
          await prisma.comissions.upsert({
            where: {
              producer: object.producer,
            },
            update: {
              rate: object.rate,
            },
            create: object,
          });
        }

I can update it, but it will take a long time to complete. I know about transaction but I don't know how to use it.

P粉478445671
P粉478445671

reply all(1)
P粉354602955

There are two ways to use transaction queries in Prisma.

Sequential operations: Pass an array of Prisma client queries to be executed sequentially within a transaction.

Interactive transactions: Pass a function that can contain user code, including Prisma client queries, non-Prisma code, and other control flow to be executed in the transaction.

In our case we should use interactive transactions because it contains user code, to use callback functions in Prisma transactions we need to add preview functionality to the Prisma.schema file

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["interactiveTransactions"]
}
prisma.$transaction(async(prisma) => {
  try {
        for (let object of updateBody) {
          await prisma.comissions.upsert({
            where: {
              producer: object.producer,
            },
            update: {
              rate: object.rate,
            },
            create: object,
          });
        }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!