访问Sequelize模型挂钩功能中的其他模型



我正在尝试创建一个模型挂钩,该挂钩在创建主模型时自动创建关联的记录。当我的模型文件结构如下时,我如何访问钩子函数中的其他模型?

/**
 * Main Model
 */
module.exports = function(sequelize, DataTypes) {
  var MainModel = sequelize.define('MainModel', {
    name: {
      type: DataTypes.STRING,
    }
  }, {
    classMethods: {
      associate: function(models) {
        MainModel.hasOne(models.OtherModel, {
          onDelete: 'cascade', hooks: true
        });
      }
    },
    hooks: {
      afterCreate: function(mainModel, next) {
        // ------------------------------------
        // How can I get to OtherModel here?
        // ------------------------------------
      }
    }
  });

  return MainModel;
};

您可以通过sequelize.models.OtherModel访问其他模型。

您可以使用this.associations.OtherModel.target

/**
 * Main Model
 */
module.exports = function(sequelize, DataTypes) {
  var MainModel = sequelize.define('MainModel', {
    name: {
      type: DataTypes.STRING,
    }
  }, {
    classMethods: {
      associate: function(models) {
        MainModel.hasOne(models.OtherModel, {
          onDelete: 'cascade', hooks: true
        });
      }
    },
    hooks: {
      afterCreate: function(mainModel, next) {
        /**
         * Check It!
         */
        this.associations.OtherModel.target.create({ MainModelId: mainModel.id })
        .then(function(otherModel) { return next(null, otherModel); })
        .catch(function(err) { return next(null); });
      }
    }
  });

  return MainModel;
};

最新更新