1. 钩子(Hooks)
几个钩子函数的是有执行顺序的,一定要注意。
(1)
beforeBulkCreate(instances, options, fn)
beforeBulkDestroy(options, fn)
beforeBulkUpdate(options, fn)
(2)
beforeValidate(instance, options, fn)
(-)
validate
(3)
afterValidate(instance, options, fn)
- or -
validationFailed(instance, options, error, fn)
(4)
beforeCreate(instance, options, fn)
beforeDestroy(instance, options, fn)
beforeUpdate(instance, options, fn)
beforeSave(instance, options, fn)
beforeUpsert(values, options, fn)
(-)
create
destroy
update
(5)
afterCreate(instance, options, fn)
afterDestroy(instance, options, fn)
afterUpdate(instance, options, fn)
afterSave(instance, options, fn)
afterUpsert(created, options, fn)
(6)
afterBulkCreate(instances, options, fn)
afterBulkDestroy(options, fn)
afterBulkUpdate(options, fn)
遇到的问题:设置了beforeUpdate的钩子函数,update时总是调用不到。
原因:
// 先触发了beforeBulkUpdate钩子
MyModel.update(mModel,
{where:{col_1 : val_1}}
);
解决:
// 强制为每一行都更新
beforeBulkUpdate: function(options){
options : { individualHooks : true }
}
// 或者在每一次update时激活这个options
MyModel.update(mModel, { where: {col_1 : val_1}, individualHooks: true });
参考:
[1] Sequelize doc - update(values, options)