Home > other >  How can I cascade delete with one-to-many relation in typeORM?
How can I cascade delete with one-to-many relation in typeORM?

Time:02-23

I have group and contact entities in OneToMany relationship. I add contacts within the group. When I want to delete, I want both sides of the database to be deleted. but only the group table is deleted.

here's contact.entity contact.entity

Here's one to many relationship:

here's group.entity group.entity

The function I wrote in the service is as follows: function in the service

I tried many solutions by searching. Adding cascades on both sides, I know this isn't right, but I wanted to try, but I couldn't get it to work.

CodePudding user response:

you are using it wrong way. If you hover to softDelete function, you will see it need props like: (method) Repository<Group>.softDelete(criteria: string | number | Date | ObjectID | string[] | FindConditions<Group> | number[] | Date[] | ObjectID[] hovered

which mean you have to use it like :

getRepository(Group).softDelete({ id: groupId})

same as update function: update

getRepository(Group).update({id: groupId}, {name: "new name"})

CodePudding user response:

Don't hard code something it can be done by the database itself. If you want all the contacts of the group to be deleted while the group is deleted then use foreign key with

on delete cascade

eg:

create table group1(
id serial primary key,
name varchar
);

create table contact(
id serial primary key,
name varchar,
group_id integer references group1 (id) on delete cascade
);

Result here

  • Related