Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM Cascade Delete

Am having troubles deleting my entities, i have the following partial codes

@ManyToOne(type => Comment, comment => comment.replies, {
    onDelete: "CASCADE"
})
parent: Comment;

and

@OneToMany(type => Comment, comment => comment.parent)
replies: Comment[];

I have tried manager.remove(comment) and

await manager
    .createQueryBuilder()
    .delete()
    .from(Comment)
    .where("id = :id", { id: comment.id })
    .execute();

Both don't work, is there something am doing wrong, how do I go about this, here is my select query

let comment = await manager
    .createQueryBuilder(Comment, "comment")
    .leftJoinAndSelect("comment.user", "user")
    .where("comment.id = :id", { id: request.body.comment })
    .getOne();

The error am getting is

UnhandledPromiseRejectionWarning: QueryFailedError: ER_ROW_IS_REFERENCED_2: Cannot delete or update a parent row: a foreign key constraint fails

Thanks in advance.

like image 467
lulliezy Avatar asked Mar 19 '18 12:03

lulliezy


3 Answers

Apparently i had to delete all tables and do a fresh migration for the onDelete: "CASCADE" to take effect but worked

like image 119
lulliezy Avatar answered Oct 19 '22 22:10

lulliezy


next time, change property "onDelete" in your models, and create a migration to change it on your database.

like image 3
Patricio León Avatar answered Oct 19 '22 21:10

Patricio León


It could be that you have the following decorator in an entity.

  @DeleteDateColumn()
  deletedAt: Date;

If you have this decorator and then have is turned on in a service. You'll see that it respects the deletedAt time and doesn't actually remove it from the db, but instead the services will automatically not return it if respecting the flag.

{ useSoftDelete: true })

Next I would check what is actually set in the database. If you are using synchronize true then it might reflect correctly, but you should use a migration to create everything for production purposes or risk data loss.

Cheers and good luck mate!

like image 1
Urasquirrel Avatar answered Oct 19 '22 22:10

Urasquirrel