首页 > 解决方案 > 使用 sequelize 事务记录对象数组

问题描述

我需要在 sequelize 事务中记录一组对象。

我有一个续集交易,我在其中记录了一个项目(例如)。然后我需要记录一些任务,我用 bulkCreate 完成了,但后来我意识到我直接从模型 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 上取消交易

标签: mysqlnode.jstransactionssequelize.js

解决方案


嘿,我必须做类似的事情,我还没有做到,但我当时已经阅读了它,示例如下

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
});

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


推荐阅读