ウェブサイト検索

node.js - TypeORM カスケード削除


エンティティを削除するのに問題があり、次の部分的なコードがあります

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

そして

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

私は manager.remove(comment) を試しました、そして

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

どちらも動きません。私が何か間違っているのでしょうか。これをどのように進めればいいですか。こちらが私のセレクトクエリです。

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

私が受けているエラーは

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

よろしくお願いします。

回答 #1

どうやら、onDelete: "CASCADE" を有効にするには、すべてのテーブルを削除して新たにマイグレーションする必要があったようですが、うまくいきました

回答 #2

次回、モデルの「onDelete」プロパティを変更し、データベースでそれを変更するマイグレーションを作成してください。

関連記事