Skip to content

Cascade delete does not work unless relation is optional #2212

@dodas

Description

@dodas

Bug description

When I set db CONSTRAINT to CASCADE on delete and relation is marked as required in schema, prisma errors with

The change you are trying to make would violate the required relation 'UserToPost' between the `User` and `Post` models.

It works when I set the foreign key and the relation field as optional in prisma schema.

How to reproduce

  1. Set delete behaviour to cascade in db:
ALTER TABLE public.Post
DROP CONSTRAINT Post_authorId_fkey,
ADD CONSTRAINT Post_authorId_fkey
   FOREIGN KEY (authorId)
   REFERENCES public.User (id)
   ON DELETE CASCADE
   ON UPDATE CASCADE;
  1. create at least one User and one Post that belongs to him.
  2. try to delete that User with prisma client

Expected behavior

The user and all his posts should be deleted.

Prisma information

schema:

model User {
  id        Int      @id @default(autoincrement())
  posts     Post[]
}

model Post {
  id        Int   @id @default(autoincrement())
  author    User  @relation(fields: [authorId], references: [id])
  authorId  Int
}

Environment & setup

DB: Postgres 11.4
Prisma: 2.0.0-beta.2
Node: 12.2.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions