gpt4 book ai didi

mysql - 使用 Sequelize 事务记录对象数组

转载 作者:行者123 更新时间:2023-11-29 16:07:35 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

在我看来,上面的评论可能是你的问题...“确保退回它们”...你可能错过了链的第二部分的返回

关于mysql - 使用 Sequelize 事务记录对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com