删除父级时隔离孤儿

时间:2020-11-12 18:09:38

标签: mysql node.js sequelize.js

我在mysql中有两个表:

create table comments
(
    id                 int unsigned auto_increment primary key,
    postId             varchar(100)                not null,
    text               text                        not null,
    constraint commentForPost foreign key (postId) references posts (id)
);

create table post
(
    id               varchar(100)                        not null primary key,
    name             varchar(100)                        not null,
);

和以下两个以下模型: post.js文件:

class Post extends Model {}

Post.init({
    // Model attributes are defined here
    id: {
        type: DataTypes.STRING,
        primaryKey: true
    },
    name: {
        type: DataTypes.STRING,
    }
}, {
    // Other model options go here
    sequelize, // We need to pass the connection instance
    modelName: 'Post', // We need to choose the model name
    tableName: 'posts',
    timestamps: false
});


Post.hasMany(Comment, { foreignKey: 'postId', onDelete: 'CASCADE'})
Comment.belongsTo(Post, { foreignKey: 'postId' });

comment.js文件:

class Comment extends Model {}
Comment.init({
    // Model attributes are defined here
    id: {
        type: DataTypes.STRING,
        primaryKey: true
    },
    postId: {
        type: DataTypes.STRING,
        allowNull: false
    },
    text: {
        type: DataTypes.text,
        allowNull: false
    }
}, {
    // Other model options go here
    sequelize, // We need to pass the connection instance
    modelName: 'Comment', // We need to choose the model name
    tableName: 'comments',
    timestamps: false
});

现在,我想在删除帖子时删除帖子的评论。我正在使用的代码如下:

  const post = await Post.destroy({
    where: {id}
  });

这将生成以下查询:

DELETE FROM `posts` WHERE `id` = '1'

我得到的错误如下:

UnhandledPromiseRejection警告:SequelizeForeignKeyConstraintError: 无法删除或更新父行:外键约束失败 (dbcomments,约束commentForPost外部密钥(postId) 参考文献postsid))

我的续集版本是: 6.3.5

如何实现删除帖子以及删除“孤立”评论?

1 个答案:

答案 0 :(得分:0)

您指示onDelete: 'CASCADE',此选项将起作用,但仅适用于sequelize.sync呼叫(使用此选项创建外键)。通常的destroy呼叫不考虑此选项。因此,您应该手动更改现有外键以设置ON DELETE CASCADE

相关问题