【问题标题】:Sequelize hook afterUpdate How to get dirty fields, original value and updated value?Sequelize hook afterUpdate 如何获取脏字段、原始值和更新值?
【发布时间】:2017-06-07 02:04:59
【问题描述】:

我被 sequelize hooks 困住,试图将模型的每个更改写入日志表。因此,我正在寻找一种在写入 MySQL 之前和之后访问模型数据的方法。

如何在更新后的 Sequelize Hook 中访问这些数据?

如何获取更新/更改/脏字段?

如何访问更新前后的数据以进行比较?

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    使用instance.dataValuesinstance._previousDataValues 在对象更新前后访问值。这对例如钩子有效,而不是散装钩子。取自Sequelize Hooks- Previous data values for afterBulkUpdate

    【讨论】:

      【解决方案2】:
          module.exports = (sequelize, DataTypes) => {
              const ContractLineItem = sequelize.define('ContractLineItem', {
                  id: {
                      type: DataTypes.INTEGER,
                      field: 'id',
                      allowNull: false,
                      primaryKey: true,
                      autoIncrement: true
                  }
                  //more attributes here
              }, {
                  schema: 'public',
                  tableName: 'ContractLineItem',
                  timestamps: true
              });
      
      
              ContractLineItem.beforeBulkUpdate((contractLineItem, options) => {    
                  console.log("b4 update contractLineItem....contractLineItem._change =" + contractLineItem._change);
      
                  if (!contractLineItem._change){
                      console.log("nothing changed.............");
                      //skip updating record
                      //return next();
                  }else{
                      console.log("something changed................");
                      //update record
                  }
                  console.log("after checking on change....");
              });
      
              ContractLineItem.associate = (models) => {
      
                  ContractLineItem.belongsTo(models.Contract, {
                      foreignKey: 'contractId',
                  });
                  //more relationships
      
              };
              return ContractLineItem;
          };
      

      【讨论】:

      • 控制台日志的输出是:b4 update contractLineItem..contractLineItem._change =undefined,知道为什么它是未定义的吗?
      • 因为你应该使用._changed 而不是._change
      【解决方案3】:

      钩子函数的第一个参数是实例。只要在更新操作之前获取实例,instance._previousDataValuesinstance._change 就可用。

      sequelize.addHook(
        "afterCreate",
        (i) => {
          console.log(i);
        }
      );
      

      【讨论】:

      • instance._changed 可用,而不是_change
      猜你喜欢
      • 2011-04-08
      • 2014-12-24
      • 1970-01-01
      • 2013-09-22
      相关资源
      最近更新 更多