Reputation: 5662
How I know inside a hook afterBulkUpdate() if instance User updated or not?
UserController.js
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
// But inside a Model how I know if updated or not?
User.addHook('afterBulkUpdate', (options) => {
// user.isUpdated?
});
I couldn't use afterUpdate(), doesn't run to me, even using individualHooks: true
like this:
UserController.js
const [isUpdated] = await User.update(
fields,
{where, individualHooks: true}
);
I am using MySQL. Any solution?
Upvotes: 0
Views: 1477
Reputation: 4434
const user = sequelize.define("user",
{
first_name: { type: DataTypes.STRING, trim: true },
...
},
hooks: {
// afterUpdate(instance, options) {
// let changed = instance._changed;
// console.log(changed, options);
// }
},
}
);
Upvotes: 1
Reputation: 5662
After @Wang Liang answer, I concluded:
beforeUpdate()
execute only if WHERE of SQL is true.
afterUpdate()
also execute only if WHERE of SQL is true.
Example:
const [isUpdated] = await User.update(
fields,
{
individualHooks: true, // Needs to execute `beforeUpdate()` and `afterUpdate()`
where: {
userId: 0 // ID does not exists in DB
}
});
In this case beforeUpdate()
and afterUpdate()
does not execute, because userId = 0
is false
. Can be with another condition false on WHERE.
Remember: isUpdated
return number of affected rows. Not if can updated or not (because of WHERE).
beforeBulkUpdate()
is always executed after update no mather what.
afterBulkUpdate()
is always executed before update no mather what.
So my solution is:
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
});
On Controller:
const [isUpdated] = await User.update(
fields,
{
individualHooks: true, // remember this
where
});
console.log(User.updated);
console.log(isUpdated);
User.updated = true
isUpdated = 0
User.updated = true
isUpdated = N
(N is affected rows)User.updated = false
isUpdated = 0
User.updated = false
isUpdated = 0
Of course when WHERE is false, does not mather is has changed data or not.
Upvotes: 1