how to delete relational item in prisma2

1.7k views Asked by At

My data model includes the following nodes:

model User {
  id           Int @id @default(autoincrement())
  name         String
  posts        Post[]
}
model Post {
  id           Int @id @default(autoincrement())
  body         String
  user         User @relation(fields: [userId], references: [id])
  userId       Int
}

I tried to delete one User like this:

async function deleteUser(_, args) {
    const { id } = args
    return prisma.user.delete({
      where: { id: id }
    })
  }

But it gives an error: ... The change you are trying to make would violate the required relation UserToPost between the User and Post models.

Then how to delete one user? Even I tried to delete the post first then the user but again same error happened.

2

There are 2 answers

0
sameer kashyap On

Looks like your table does not support CASCADE deletions and prisma does not automatically add it for you. You will have to manually update the definition of your table either while migration or after the fact.

so basically, alter your table definition.

ALTER TABLE public.Post
DROP CONSTRAINT Post_user_fkey,
ADD CONSTRAINT Post_user_fkey
   FOREIGN KEY (user)
   REFERENCES public.User(user)
   ON DELETE CASCADE
   ON UPDATE CASCADE;

Refer to these docs on options of configuring relational queries.

0
Suchismita Goswami On

This has now been released as a preview feature behind a preview feature flag. You can read about it in the release notes for 2.26.0: https://github.com/prisma/prisma/releases/tag/2.26.0

The preview feature can be enabled by setting the preview feature flag referentialActions in the generator block of Prisma Client in your Prisma schema file:

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["referentialActions"]
}