TypeORM Tree cascade remove

Viewed 1104

Hi guys Im using TypeORM Materialized Tree from their docs:

https://github.com/typeorm/typeorm/blob/master/docs/tree-entities.md#materialized-path-aka-path-enumeration

Now I would like to Remove some Root Tree node and also to remove all of it children, Im using repository like this:

await repository.remove(TreeNode);

But Im getting cannot remove because of foreign key constraints, I passed cascade: true like this:

Column({
    length: 500,
    default: '',
  })
  name: string

@TreeParent()
  parent: Comment

  @TreeChildren({
    cascade: true,
  })
  children: Comment[]

But it is not taking any effect ???

3 Answers

I think I had a similar issue.
I got these kind of errors when I tried to remove parent entity.

After I user TreeRepostitory's findDescendants, which will populate entity's child entities, remove works fine.

update or delete on table "mytable" violates foreign key constraint Key (id)=(17) is still referenced from table "mytable"

let treeRepo = getManager().getTreeRepository(MyEntity);
await treeRepo.findDescendants(entity)
treeRepo.remove(entity)
@TreeParent({ onDelete: 'CASCADE' })

So this answer is inspired by the previous answer from @rooste.

After I tried his solution I still faced the foreign key constrain problem, also await treeRepo.findDescendants(entity) was getting, well, the Descendants. Without the parent node (the entity) itself.

So I implemented the following solution (manager = getManager();)

 async delete(id: number) {
    const productsTree = await this.manager.getTreeRepository(ProductEntity);
    const nodeToBeDeleted = await this.manager.getTreeRepository(ProductEntity).findOne(id);
    await this.manager.query("SET foreign_key_checks = 0;");
    const res = await productsTree.remove(await productsTree.findDescendants(nodeToBeDeleted));
    await this.manager.query("SET foreign_key_checks = 1;");
    return {
      result: res.length > 0? 'Deleted successfully' : 'Already deleted'
    }
  }

By disabling the foreign key constrain just temporarily and deleting the main node and its children one after another, I was able to get around this issue, but I agree with you typeORM can really suck in some cases.

I don't know if it's the best workaround in the world, so let me know if it works for you!

Related