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