【问题标题】:Sequelize orphan removal when deleting parentSequelize 删除父项时删除孤儿
【发布时间】:2020-11-13 03:17:13
【问题描述】:

我在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,
);

以及以下两个模型在 sequelize 中: 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
});

现在我想在删除帖子时删除帖子的 cmets。我使用的代码如下:

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

这会生成以下查询:

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

我得到的错误如下:

UnhandledPromiseRejectionWarning: SequelizeForeignKeyConstraintError: 无法删除或更新父行:外键约束失败 (db.comments, 约束 commentForPost 外键 (postId) 参考posts (id))

我的sequelize版本是:6.3.5

如何实现删除帖子同时删除“孤儿”cmets?

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    您指定了onDelete: 'CASCADE',此选项将起作用,但仅适用于sequelize.sync 调用(使用此选项创建外键)。通常的destroy 调用不考虑此选项。所以你应该手动改变一个现有的外键来设置ON DELETE CASCADE

    【讨论】:

    • 您能否提供一个代码示例来说明我如何实现这一目标?
    • 首先删除一个外键 ALTER TABLE comments DROP FOREIGN KEY commentForPost 然后使用 CASCADE 选项再次创建它:ALTER TABLE comments ADD CONSTRAINT commentForPost FOREIGN KEY (postId) references posts (id) ON DELETE CASCADE。可能这两个命令有点不准确,请查看 MySQL 文档
    猜你喜欢
    • 2017-09-27
    • 2011-01-02
    • 2012-10-22
    • 2012-02-07
    • 2010-09-23
    • 2014-10-07
    • 2013-06-05
    • 2011-02-09
    • 2012-08-16
    相关资源
    最近更新 更多