Access to other models in the Sequelize model capture function

I am trying to create a model hook that automatically creates a linked record when the main model was created. How can I access my other models in the hook function when my model file is structured as follows?

/** * 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; }; 
+5
source share
2 answers

You can access another model using sequelize.models.OtherModel .

+16
source

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; }; 
+3
source

Source: https://habr.com/ru/post/1216336/


All Articles