I\'m trying to create a trigger using sequelize.. the main idea is to create an instance of CONFIG
after creating a USER
.
// USER MODEL
You can do this in one of two ways. As you noted, you could create a trigger in the database itself. You could run a raw sequelize query to accomplish this:
sequelize.query('CREATE TRIGGER create_config AFTER INSERT ON users' +
' FOR EACH ROW' +
' BEGIN' +
' insert into configs (UserId) values(new.id);' +
'END;')
Or, you could create a hook on the user model that performs an action on an afterCreate
event:
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
name : DataTypes.STRING(255),
email : DataTypes.STRING(255),
username : DataTypes.STRING(45),
password : DataTypes.STRING(100),
}, {
classMethods : {
associate : function(models) {
User.hasOne(models.Config)
}
},
hooks: {
afterCreate: function(user, options) {
models.Config.create({
UserId: user.id
})
}
}
});
return User;
};