sequelize:删除与belongsToMany关联的级联

时间:2018-03-13 13:40:40

标签: node.js database sequelize.js

在以下简单案例中:
- 产品可以有很多图像
- 图像可以有很多产品
我删除产品时尝试使用删除级联来删除相关图像。

var product = sequelize.define('product', {
    name: Sequelize.DataTypes.STRING,
});

var image = sequelize.define('image', {
    name: Sequelize.DataTypes.STRING,
});

// setup relations
image.belongsToMany(product, {
    through: 'productImage',
    onDelete: 'cascade',
});

product.belongsToMany(image, {
    through: 'productImage',
    onDelete: 'cascade',
});

// create tables
await sequelize.drop({ force: true });
await sequelize.sync();

// create some data
await product.create({
    name: 'product1',
    images: [
        { name: 'image1' },
        { name: 'image2' },
    ]
},{
    include: [{ model: image }]
});

// find and delete the product
var prod = await product.findById(1);
await prod.destroy();

此处删除产品,删除productImage关系,但图像仍在此处 当没有任何内容引用时,如何告诉sequelize还删除图像?

0 个答案:

没有答案