Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize afterCreate not firing

I am using Sequelize as an ORM with MySQL, Node and Express.

When inserting a new item to 'ExpertiseField' table, I want to update a field in a different table.

I'm having an issue with hooks in Sequelize, for some reason afterCreate appears to not do anything.

My 'ExpertiseField' model:

module.exports = (sequelize, DataTypes) => {
  const ExpertiseField = sequelize.define('ExpertiseField', {
    name: DataTypes.STRING,
    type: DataTypes.INTEGER,
    position: DataTypes.INTEGER
  }, {
    classMethods: {
      associate: function(models) {
        ExpertiseField.hasOne(models.LocalDataLastUpdatedAtItem);
      }
    },
    hooks: {
      afterCreate: function(expertiseField, options) {
        sequelize.models.LocalDataLastUpdatedAtItem.update({
          updatedAt: expertiseField.updatedAt
        },{
          where: {
            name: 'expertise_fields_last_updated_at'
          }
        });
      }
    }
  });
  ExpertiseField.associate = function(models) {
    // associations can be defined here
  };
  return ExpertiseField;
};

the hook I'm creating isn't doing anything, any idea why?

like image 648
JozeRi Avatar asked Mar 25 '26 01:03

JozeRi


1 Answers

Answering my question so maybe it helps someone from making my mistake in the future.

Apparently Sequelize hooks works inside the code only. When editing my table from a 3rd party SQL-Viewer program nothing happened and I thought something was wrong.. but when running my code everything worked fine.

like image 66
JozeRi Avatar answered Mar 27 '26 14:03

JozeRi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!