且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Typeorm 级联删除

更新时间:2023-02-05 11:39:07

显然我必须删除所有表并为 onDelete: "CASCADE" 重新迁移才能生效但有效>

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.

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