search

Home  >  Q&A  >  body text

How to update multiple rows with different data in Prisma

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粉478445671P粉478445671433 days ago731

reply all(1)I'll reply

  • P粉354602955

    P粉3546029552023-12-26 09:37:44

    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,
              });
            }
    });

    reply
    0
  • Cancelreply