How to create TRIGGER in SEQUELIZE (nodeJS)?

I am trying to create a trigger using sequelize .. The main idea is to create a CONFIG instance after creating the USER.

//USER MODEL 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) } } }); return User; }; //CONFIG MODEL module.exports = function(sequelize, DataTypes) { var Config = sequelize.define('Config', { notifications : DataTypes.INTEGER }, { classMethods : { associate : function(models) { Config.belongsTo(models.User) } } }); return Config; }; 

As you can see, the "user" has one "config", and the "config" belongs to the "user", so after creating the user, I want to automatically create his configuration line.

The goal is to do:

 DELIMITER // CREATE TRIGGER create_config AFTER INSERT ON user FOR EACH ROW BEGIN insert into config (user_id) values(new.user_id); END; // DELIMITER ; 

Now, what am I doing to simulate the following:

 .then(function(user){ return dao.Config.create(req.body, user, t); }) 

Once the user is created, I create his configuration similar to this ... it works, but is not what I am looking for.

How would I do that?

Thanks!

+8
mysql triggers
source share
1 answer

You can do this in one of two ways. As you noticed, you could create a trigger in the database itself. To run this query, you can run a raw secelize request:

 sequelize.query('CREATE TRIGGER create_config AFTER INSERT ON users' + ' FOR EACH ROW' + ' BEGIN' + ' insert into configs (UserId) values(new.id);' + 'END;') 

Or you can create a hook in a custom model that takes an action after a create event occurs:

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

All Articles