【发布时间】:2022-03-23 14:10:33
【问题描述】:
我是 Sequelize 的新手。我有 2 个模型:Category 和 User 像这样:
const Category = sequelize.define('Category', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: DataTypes.STRING,
displayName: DataTypes.STRING
});
Category.associate = (models) => {
models.Category.hasMany(models.Post, { foreignKey: 'categoryId' });
};
const Post = sequelize.define('Post', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
title: DataTypes.STRING,
content: DataTypes.STRING
});
Post.associate = (models) => {
models.Post.belongsTo(models.Category, {
foreignKey: 'categoryId',
onDelete: 'CASCADE'
});
};
上面的初始化代码确实创建了 2 个表,categoryId 作为外键引用 Category 的 Post。但生成的脚本包括:
FOREIGN KEY (`categoryId`) REFERENCES `Categories` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
而不是ON DELETE CASCADE。请告诉我这里出了什么问题以及如何在该外键属性上设置ON DELETE CASCADE。
【问题讨论】:
-
我认为您需要在 Category 模型上添加 on delete 选项,请查看this answer (Possible Duplicate)
标签: javascript mysql node.js express sequelize.js