How make a properly update method on prisma

Viewed 14

I want to fix my PUT method on prisma to update all plans connections when updating my checkout

this.connection.update({
      where: { id },
      data: {
        name,
        description,
        picture,
        updatedAt: new Date(),
        plans: {
          connect: plans.map((id) => ({ id })),
        },
      },
      include: {
        plans: true,
      },
    });

my update is like this, but i found a problem: When i pass on the request an array of plans ID's with less plans (deleting) it doesnt delete the ones i already have connected. I know there is the disconect, but there is a way to update all connects when passing that data? What i mean is: i want to full replace the connections of the plan when updating it.

Thnks!

1 Answers

It would be helpful to know your schema.

E.g. it is unclear, whether you only want to remove the link between connection and plan but keep the removed plans in the database or you want to delete the plans.

A very frequent case is a 1:n relationship, i.e. your plan has a connectionId that establishes this relationship and you would want to delete plans that are to be removed. I'll assume this is your situation as well.

Please comment or edit your question (and share your schema) if your situation is different.

In this case, I'd recommend to delete the removed plans before you update the connection. You would delete all plans that have the connectionId that is currently being updated, but whose planId is not in the "new" plans:

await prisma.plan.deleteMany({
  where: {
    connectionId: id,
    id: { notIn: plans },
  },
});

If your use case is different, there is a disconnect similarly to the connect you are already using. But as you mentioned, you would have to find out, which relations to disconnect by yourself. E.g. by comparing what is currently in the database and what is in the "new" object.

Related