Accessing other models in a Sequelize model hook function

前端 未结 2 1549
北恋
北恋 2021-02-19 13:05

I\'m trying to create a model hook that automatically creates an associated record when the main model has been created. How can I access my other models within the hook functio

相关标签:
2条回答
  • 2021-02-19 13:54

    You can use 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;
    };
    
    0 讨论(0)
  • 2021-02-19 13:57

    You can access the other model through sequelize.models.OtherModel.

    0 讨论(0)
提交回复
热议问题