在Sequelize模型钩子函数中访问其他模型

我试图创build一个模型钩子,当主模型已经创build时自动创build一个关联的logging。 当我的模型文件结构如下时,如何在钩子函数中访问我的其他模型?

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

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

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