Search code examples
prismaprisma2

How to update many-to-one relation?


My schema looks like this

model Article {
  id          String  @id
  title        String
  isPublished Boolean @default(false)

  comments Comment[]
}

model Comment {
  id    String @id
  content  String
  articleId String

  article Article @relation(fields: [articleId], references: [id])
}

And I am using the upsert like this

prisma.article.upsert({
where: {id},
create: {// create code here},
update: {
comments: {createOrConnect: [{...}]}
}
})

But when removing the comment, this code does not work. As I can see, the code does not have any disconnect.

I want to delete the comment on disconnecting, but don't know how.

So I have 2 questions:

  1. How to delete a record on disconnecting
  2. Does Prisma auto-detect the removed comments, since they are not in the article comments array anymore? If it does not, what is the best practice to detect this?

Solution

  • You can delete the comments first:

    prisma.comment.deleteMany({ where: { articleId: id } })
    

    And it will remove automatically al the comments from the article because of the ON DELETE CASCADE

    I am assuming that you are using mysql or postgres