0

I want to re-create some related records on update, something like this:

db.post.update({
  where: { id: 1 },
  data: {
    title: "The first post",
    comments: {
      set: [{ content: "foo"}, { content: "bar" }],
    },
  },
})

This is unfortunately not possible as set only allows to reference existing comments (by using the id). So is there another way during an update to delete all those related comments and re-create them from scratch in one transaction (and maybe on nested write)?

medihack
  • 16,045
  • 21
  • 90
  • 134

1 Answers1

1

I assume you are referring to Prisma ORM.

In order to re-create related records (i.e. delete previous related records and add new ones) you will need to use deleteMany along with create, something like this:

db.post.update({
  where: { id: 1 },
  data: {
    title: "The first post",
    comments: {
      // delete existing relations
      'deleteMany': {},
      // create new relations
      'create': [
         ......your new data here....
      ],
    },
  },
})

See this comment on github for an update example.

  • Cool, I thought about this, but it isn't documented anywhere in the docs. I'll open a issue to add this to the docs or to introduce a replace keyword like mentioned in your linked issue. Thanks for the help! – medihack Aug 01 '21 at 11:55