Filip Pham
Filip Pham

Reputation: 41

Delete Prisma self-referencing (one to many)

I have this prisma schema

model Directory {
  id                String      @id @default(cuid())
  name              String?
  parentDirectoryId String?
  userId            String
  parentDirectory   Directory?  @relation("parentDirectoryId", fields: [parentDirectoryId], references: [id], onDelete: NoAction, onUpdate: NoAction)
  user              User        @relation(fields: [userId], references: [id], onDelete: Cascade)
  quizess           Quiz[]
  subDirectory      Directory[] @relation("parentDirectoryId")

  @@index([parentDirectoryId])
  @@index([userId])
}

The logic behind it: I can have a folder that can be in root (parentDirectoryId = null) or it can have many additionals directories.

How do I delete directory with directiories inside of them?

This is what happens when I try to call prisma.delete:

Invalid prisma.directory.delete()` invocation:

The change you are trying to make would violate the required relation 'parentDirectoryId' between the Directory and Directory models.`

Set onDelete: Cascade, onUpdate: Cascade which doesnt work

Upvotes: 4

Views: 871

Answers (1)

try this:


let directories = await this.prisma.directory.findFirst({
        where: { id: directory.id },
        include: { subDirectory: true },
      });

prisma.directory.update({
   data: {
           subDirectory: {
               disconnect: directories.subDirectory.map((e) => {
                  return { id: e.id };
               }),
            },
          },
})

The directory is the father directory.

Upvotes: 0

Related Questions