取决于交易的挂钩

Jac*_*cob 5 hook transactions node.js sequelize.js

我想在用户模型上的afterCreate上创建一个sequelize挂钩。当我只创建没有交易的用户时,它的工作效果很好。但是,如果我在事务中运行我的create语句,则挂钩将在提交之前运行。

用户模型挂钩

hooks: {
    afterCreate: userModule.NewUserHook,
    afterBulkCreate: userModule.NewUserHook
}
Run Code Online (Sandbox Code Playgroud)

挂钩功能

NewUserHook: function NewUserHook(user, options){
    console.log('Inside hook');
}
Run Code Online (Sandbox Code Playgroud)

可以在options.transaction中访问该事务。

提交事务后,是否仍要运行挂接?

Ale*_* F. 5

游戏有点晚了,但是由于我在寻找答案时遇到了这个问题,因此这个问题可能对其他人有用。

如果在事务内部创建用户,则事务对象将在挂钩回调的参数之一(取决于版本)中传递。链接到docs。直接从源链接复制以下内容:

// Here we use the promise-style of async hooks rather than
// the callback.
User.hook('afterCreate', (user, options) => {
  // 'transaction' will be available in options.transaction

  // This operation will be part of the same transaction as the
  // original User.create call.
  return User.update({
    mood: 'sad'
  }, {
    where: {
      id: user.id
    },
    transaction: options.transaction
  });
});


sequelize.transaction(transaction => {
  User.create({
    username: 'someguy',
    mood: 'happy',
    transaction
  });
Run Code Online (Sandbox Code Playgroud)

如果User.update在前面的代码中对的调用中未包含交易选项,则不会发生任何更改,因为在提交未决交易之前,数据库中不存在新创建的用户。