使用顺序事务记录对象数组

时间:2019-04-08 22:01:20

标签: mysql node.js transactions sequelize.js

我需要在连续交易中记录一组对象。

我有一个续集交易,在其中记录了一个Project(例如)。然后,我需要记录一些Tasks,我使用bulkCreate做到了,但是后来我意识到我对直接从Model Task模型调用bulkCreate的事务进行了处理。

try {
  const transaction = await db.transaction(t => {
    return Project.create(
      { ...req.body.projectFull.entity },
      { transaction: t }
    ).then(
      projectCreated => {
        let tarefas = req.body.projectFull.tasks;
        const addProjectId = function(object) {
          object.projectId = projectCreated.dataValues.id;
          return object;
        };
        let criarTarefas = tarefas.map(addProjectId);
        Task.bulkCreate(criarTarefas);
      },
      { transaction: t }
    );
  });

我希望不直接从模型中直接在我的交易中使用bulkCreate。我提供的代码可以很好地工作并记录数据,但可以在bulkCreate上为事务处理

1 个答案:

答案 0 :(得分:0)

嘿,我必须做类似的事情,但是我还没读懂,但是我当时已经读过了,例子如下

return sequelize.transaction(t => {

  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(user => {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(result => {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(err => {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

在我看来,以上评论可能是您的问题...“请确保您将它们退回” ...您可能错过了连锁店第二部分的退货