How to create a TRIGGER in SEQUELIZE (nodeJS)?

前端 未结 1 1972
难免孤独
难免孤独 2021-02-05 10:24

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         


        
1条回答
  •  孤独总比滥情好
    2021-02-05 10:53

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

    0 讨论(0)
提交回复
热议问题