Sequelize orm

时间:2017-05-30 22:55:58

标签: node.js sequelize.js cascade

我有两个用Sequelize cli创建的模型;第一个模型是user_number,第二个模型是emailSign

这是我的user_number型号:

    'use strict';
     module.exports = function(sequelize, DataTypes) {
     var user_number = sequelize.define('user_number', {
     user_id: DataTypes.INTEGER,
     callRoute_id: DataTypes.INTEGER,
     password: DataTypes.STRING,
     }, {
     underscored: true,
     classMethods: {
         associate: function(models) {
            // associations can be defined here
             user_number.hasMany(models.emailSign, {
                foreignKey: 'user_number_id',
                onDelete: "CASCADE",
             });
           }
           }
        });
      return user_number;
    };

这是我的emailSign型号:

      'use strict';
      module.exports = function(sequelize, DataTypes) {
      var emailSign = sequelize.define('emailSign', {
      email: DataTypes.STRING,
      user_number_id: DataTypes.INTEGER
      }, {
         underscored: true,
         classMethods: {
             associate: function(models) {
             // associations can be defined here
             emailSign.belongsTo(models.user_number, {
             foreignKey: 'user_number_id',

           })
         }
        }
      });
      return emailSign;
          }; 

我希望destroy user_number级联删除emailSign。我的破坏代码是

User_number.destroy({where:{id : 5}}).then(function(){

resp.status(200);
) 

user_number已删除ID为{5},但未移除emailSign

如何删除相关的emailSign

我的Sequelize版本是3.30.4

2 个答案:

答案 0 :(得分:1)

您应该在belongsTo association

上定义onDelete操作
emailSign.belongsTo(models.user_number, {
     foreignKey: 'user_number_id',
     onDelete: 'CASCADE'
});

答案 1 :(得分:0)

不确定这是否仍然是一个问题,但我也遇到了这个问题。级联选项不应大写:

onDelete: 'cascade' 

代替

onDelete: 'CASCADE'