Accessing other models in a Sequelize model hook function

前端 未结 2 1496
北恋
北恋 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;
    };
    

提交回复
热议问题