Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to upsert many fields in prisma ORM

How can I upsert many fields in prisma ORM with one query?

I don't want to use upsert fields one by one. Can I upsert all of them with one query?

like image 464
xander karimi Avatar asked Sep 01 '25 16:09

xander karimi


2 Answers

You can't do it right now in Prisma. There is createMany, updateMany and deleteMany, but no upsertMany. (Docs)

The most efficient way if you need to handle lots of data would probably be something like that:

prisma.$transaction([
  prisma.posts.deleteMany({ where: { userId: 1 } }),
  prisma.posts.createMany({
    { id: 1, title: 'first',  userId: 1 },
    { id: 2, title: 'second', userId: 1 },
    { id: 3, title: 'third',  userId: 1 },
  }),
]);

So you delete existing records and then recreate them again inside of a transaction.

like image 125
Danila Avatar answered Sep 04 '25 05:09

Danila


Depending on the database (and schema) you use, Prisma supports an optional boolean within a createMany call: skipDuplicates, see https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#createmany

Do not insert records with unique fields or ID fields that already exist. Only supported by databases that support ON CONFLICT DO NOTHING.

like image 35
Martin Avatar answered Sep 04 '25 06:09

Martin