【问题标题】:Accessing other models in a Sequelize model hook function在 Sequelize 模型挂钩函数中访问其他模型
【发布时间】:2015-06-01 13:16:39
【问题描述】:

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

/**
 * 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;
};

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

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

    【讨论】:

    • sequelize 不可用。
    • sequelize 应该在instance.sequelize 上可用(原始问题中的mainModel.sequelize)。
    【解决方案2】:

    您可以使用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;
    };
    

    【讨论】:

      猜你喜欢
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多