Prisma: Add the possibility of create or connect on update

Created on 20 Apr 2020  路  3Comments  路  Source: prisma/prisma

Problem

I'm updating a user with a list of hobbies, some can already exists and other none.

Solution

When I'm update the hobbies, I want to have the possibility to connect when the hobby is in DB or create when it's not.

Alternatives

Check for every hobbies and create them in the case they aren't in DB.

kinquestion prisma-client

Most helpful comment

Wouldn't the following query work for your use case:

 const hobbyData = [{ id: 'something' }] // get it from your source
  const user = { id: 'ck99o6i7r00003dycgyapg4cb' } // get this also from your source
  const test = await prisma.user.update({
    data: {
      hobby: {
        upsert: hobbyData.map((d) => ({
          create: d,
          update: d,
          where: { id: d.id },
        })),
      },
    },
    where: {
      id: user.id,
    },
  })

All 3 comments

This functionality is possible with the upsert query.

Please read the docs here about that: https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/crud#upsert

That's not what @ryands17 said me

In my use case, you can't do it because of the list or you have to do it with a loop

Wouldn't the following query work for your use case:

 const hobbyData = [{ id: 'something' }] // get it from your source
  const user = { id: 'ck99o6i7r00003dycgyapg4cb' } // get this also from your source
  const test = await prisma.user.update({
    data: {
      hobby: {
        upsert: hobbyData.map((d) => ({
          create: d,
          update: d,
          where: { id: d.id },
        })),
      },
    },
    where: {
      id: user.id,
    },
  })
Was this page helpful?
0 / 5 - 0 ratings