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 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;
};
exports = function(sequelize, DataTypes) { var Session = sequelize. define("Session", { success: { type: DataTypes. BOOLEAN, allowNull: false, default: false }, TeammateId: { type: DataTypes. INTEGER, allowNull: false } }, { classMethods: { associate: function(models) { Session.
A model can be synchronized with the database by calling model.sync(options) , an asynchronous function (that returns a Promise). With this call, Sequelize will automatically perform an SQL query to the database. Note that this changes only the table in the database, not the model in the JavaScript side.
Sequelize hooks are places we can write callbacks that get invoked at key points in time like afterCreate , afterDestroy , afterUpdate , and more. In Domain-Driven Design, after a transaction completes, we want to execute domain event handlers in order to decide whether we should invoke any follow up commands or not.
There are two ways you can create JOIN queries and fetch data from multiple tables with Sequelize: Create raw SQL query using sequelize. query() method. Associate related Sequelize models and add the include option in your Sequelize query method.
You can access the other model through sequelize.models.OtherModel
.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With