我怎么知道钩子afterBulkUpdate()里面的实例用户是否更新了?
UserController.js
const [isUpdated] = await User.update(
    fields,
    {where}
);
// Where I know if updated or not! isUpdated is 1 when updated, 0 when not updatedUser.js
// But inside a Model how I know if updated or not?
User.addHook('afterBulkUpdate', (options) => {
    // user.isUpdated?
});我不能使用afterUpdate(),甚至像这样使用individualHooks: true:
UserController.js
const [isUpdated] = await User.update(
    fields,
    {where, individualHooks: true}
);我正在使用MySQL。有什么解决方案吗?
发布于 2021-03-07 02:33:36
const user = sequelize.define("user",
    {
      first_name: { type: DataTypes.STRING, trim: true },
      ...
     
    },
      hooks: {
        // afterUpdate(instance, options) {
        //   let changed = instance._changed;
        //   console.log(changed, options);
        // }
      },
    }
  );发布于 2021-03-07 04:23:48
在@王亮回答之后,我总结道:
仅当WHERE of SQL为true时,才执行beforeUpdate()。
仅当WHERE of SQL为true时,才执行afterUpdate()。
示例:
const [isUpdated] = await User.update(
    fields,
    {
        individualHooks: true, // Needs to execute `beforeUpdate()` and `afterUpdate()`
        where: {
            userId: 0 // ID does not exists in DB
        }
    });在这种情况下,beforeUpdate()和afterUpdate()不会执行,因为userId = 0为false。可以在WHERE上使用另一个条件false。
记住:isUpdated返回受影响的行数。不能更新或不能更新(因为在哪里)。
beforeBulkUpdate()总是在update后执行,不管是什么。
afterBulkUpdate()总是在update前执行,不管是什么。
所以我的解决方案是:
User.addHook('beforeBulkUpdate', (options) => {
    options.model.updated = false; // Not updated yet
});
User.addHook('afterUpdate', (instance, options) => {
    options.model.updated = true; // Execute the updated, because WHERE is true
});在控制器上:
const [isUpdated] = await User.update(
    fields,
    {
        individualHooks: true, // remember this
        where
    });
console.log(User.updated); 
console.log(isUpdated);isUpdated = 0
isUpdated = 0
User.updated = true isUpdated = 0
User.updated = false falseisUpdated = 0User.updated = falsefalse当然当WHERE是假的时候,并不是已经改变了数据或者没有。
https://stackoverflow.com/questions/66509135
复制相似问题