mysql - 使用 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 上取消交易
解决方案
嘿,我必须做类似的事情,我还没有做到,但我当时已经阅读了它,示例如下
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
});
在我看来,上面的评论可能是您的问题...“确保退回它们”...您可能错过了连锁店第二部分的退货
推荐阅读
- sql - 使用列中的 DISTINCT 行递归运行 SELECT 查询
- excel - Excel VBA - 在过滤的列表对象数据中选择第一个单元格
- mysql - 如何获取查询列表及其执行次数
- gekko - Gekko 中的阶梯函数实现
- javascript - 运行构建时反应路由器动态网址不起作用
- python - 如何创建按顺序调用的对象的自定义管道?
- npm - 从代理后面进行无服务器部署?
- nginx - 我使用 nginx rewrite 从旧 URL 重定向到新 URL,现在 curl GET 和 POST 请求到旧 URL 不起作用
- android - Android 如何在设备启动时使用复选框启用/禁用启动应用程序?
- c++ - 使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题