首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Sequelize - afterBulkUpdate()如何获取更新或未更新

Sequelize - afterBulkUpdate()如何获取更新或未更新
EN

Stack Overflow用户
提问于 2021-03-07 02:19:02
回答 2查看 186关注 0票数 0

我怎么知道钩子afterBulkUpdate()里面的实例用户是否更新了?

UserController.js

代码语言:javascript
运行
复制
const [isUpdated] = await User.update(
    fields,
    {where}
);

// Where I know if updated or not! isUpdated is 1 when updated, 0 when not updated

User.js

代码语言:javascript
运行
复制
// But inside a Model how I know if updated or not?
User.addHook('afterBulkUpdate', (options) => {
    // user.isUpdated?
});

我不能使用afterUpdate(),甚至像这样使用individualHooks: true

UserController.js

代码语言:javascript
运行
复制
const [isUpdated] = await User.update(
    fields,
    {where, individualHooks: true}
);

我正在使用MySQL。有什么解决方案吗?

EN

回答 2

Stack Overflow用户

发布于 2021-03-07 02:33:36

代码语言:javascript
运行
复制
const user = sequelize.define("user",
    {
      first_name: { type: DataTypes.STRING, trim: true },
      ...
     
    },
      hooks: {
        // afterUpdate(instance, options) {
        //   let changed = instance._changed;
        //   console.log(changed, options);
        // }
      },
    }
  );
票数 2
EN

Stack Overflow用户

发布于 2021-03-07 04:23:48

在@王亮回答之后,我总结道:

仅当WHERE of SQL为true时,才执行beforeUpdate()

仅当WHERE of SQL为true时,才执行afterUpdate()

示例:

代码语言:javascript
运行
复制
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 = 0false。可以在WHERE上使用另一个条件false。

记住:isUpdated返回受影响的行数。不能更新或不能更新(因为在哪里)。

beforeBulkUpdate()总是在update后执行,不管是什么。

afterBulkUpdate()总是在update前执行,不管是什么。

所以我的解决方案是:

代码语言:javascript
运行
复制
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
});

在控制器上:

代码语言:javascript
运行
复制
const [isUpdated] = await User.update(
    fields,
    {
        individualHooks: true, // remember this
        where
    });

console.log(User.updated); 
console.log(isUpdated);

isUpdated = 0

  • When isUpdated = 0

  • When不影响任何行,但WHERE为true:User.updated = true isUpdated = 0

  • When影响任何行,WHERE为true:

  • (N是
  • )
  • When没有数据更改,WHERE为false:User.updated = false falseisUpdated = 0
  • When具有数据更改,WHERE is false:User.updated = falsefalse

当然当WHERE是假的时候,并不是已经改变了数据或者没有。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66509135

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档