mysql - 删除父级时续行孤儿移除

标签 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,
);
以及 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
});
现在我想在删除帖子时删除帖子的评论。我正在使用的代码如下:
  const post = await Post.destroy({
    where: {id}
  });
这会生成以下查询:
DELETE FROM `posts` WHERE `id` = '1'
我得到的错误如下:

UnhandledPromiseRejectionWarning: SequelizeForeignKeyConstraintError: Cannot delete or update a parent row: a foreign key constraint fails (db.comments, CONSTRAINT commentForPost FOREIGN KEY (postId) REFERENCES posts (id))


我的 Sequelize 版本是: 6.3.5
如何实现删除帖子并删除“孤儿”评论?

最佳答案

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

关于mysql - 删除父级时续行孤儿移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64809413/

相关文章:

linux - 如何在多核系统上获取 CPU 使用率

javascript - 如何在没有任何副作用的情况下更新 package-lock.json 中的单个依赖项?

node.js - Sequelize 不在 postgresql 中创建任何表

mysql - 我可以在同一个表的同一个 api 中使用多个 findAll() 来获取数据吗?

MYSQL无法为表添加索引

c# - 即使我在 SQL 控制台中测试命令文本时命令文本是正确的,我的命令文本仍然有错误

java - 如何在jComboBox中显示多个字段但只在数据库中插入一个字段?

Visual Studio 2017/19 中的 JavaScript Azure Function 支持(不是 VS Code)

mysql update_at 使用自 EPOCH 以来的毫秒数作为默认更新

c# - 如何只计算字符串中的字母?