我是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'
});
};
上面的 init 代码确实创建了 2 个表,其中categoryId
作为引用Post
Category
的外键。但生成的脚本包括:
FOREIGN KEY (`categoryId`) REFERENCES `Categories` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
而不是ON DELETE CASCADE
.请告诉我这里出了什么问题以及如何在该外键属性上设置ON DELETE CASCADE
。
-
通过 npm 安装 sequelize-cli。
创建 数据库后,制作两个模型,例如类别和产品:续集模型:创建 --名称类别 --属性名称:刺等。
确保类别模型中的静态方法"associate"包含以下内容:"static associate({Product}( {this.hasMany(Product, { foreignKey: 'categoryId', as: 'products', onDelete: 'cascade', hooks: true }(;">
对于产品模态:"static associate({Category}( {this.belongsTo(Category, { foreignKey: 'categoryId', as: 'category'}(;
还要确保您的迁移文件 -create-product.js 包含以下字段:categoryId: {type: DataTypes.INTEGER, allowNull: false}
现在运行终端命令:续集数据库:迁移
在应用程序内写下这个计数器.js:
app.delete("/category/:id", async(req, res( => { const id = req.params.id;尝试 { 常量类别 = 等待 Category.findOne({ where: { id }, include: 'products' }(; await category.destroy((;返回 res.json({ 消息: "类别已删除!} catch (err( { return res.status(500(.json({error: "Something went Wrong"}(;} })
使用命令启动应用程序:"节点应用程序.js"并在邮递员中测试级联删除。