Home > Software engineering >  Deep delete second level relationships data
Deep delete second level relationships data

Time:05-18

I have three models that are tied together with a relationships.

model Product {
  id      Int         @id @default(autoincrement())
  name    String
  type_id Int
  type    ProductType @relation(fields: [type_id], references: [id])
  tickets Ticket[]
}

model ProductType {
  id               Int       @id @default(autoincrement())
  name             String
  asigned_products Product[]
}

model Ticket {
  id          Int            @id @default(autoincrement())
  title       String
  description String
  priority    TicketPriority
  type        TicketType
  product_id  Int
  product     Product        @relation(fields: [product_id], references: [id])
  files       File[]
}

In order to delete the ProductType I need to delete the products referring to it, where again I need to delete the Tickets referring to these products.

I know it is possible to delete products in this way, but is it possible to go deeper and delete Tickets too?

await this.prismaService.productType.update({
            where: { id },
            data: { asigned_products: { deleteMany: {} } }
        });

        const deletedProductType = await this.prismaService.productType.delete({
            where: { id }
        });

Is it possible to do this with prisma?

CodePudding user response:

Maybe you are looking for cascading deletes, which in your case would be

model Ticket {
  id          Int            @id @default(autoincrement())
  title       String
  description String
  priority    TicketPriority
  type        TicketType
  product_id  Int
  product     Product        @relation(fields: [product_id], references: [id], onDelete: Cascade)
  files       File[]
}

In this case, adding onDelete: Cascade to the product field on the Ticket model means that deleting the Product record will also delete all related Ticket records.

Prisma docs on referential actions:
https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions

  • Related