javascript - 如何在sequelize中使用事务?
问题描述
我使用 sequelize 为 MySQL 数据库编写了两个类和迁移文件。如何使用 node.js 中的事务保存用户和他的孩子?我想创建一个类,我可以在其中将所有数据库通信封装在一个文件中,然后从我的 CRUD 方法中调用它。
用户类:
'use strict';
module.exports = function(sequelize, DataTypes) {
const User = sequelize.define('User', {
id : {
type: DataTypes.INTEGER(11),
allowNull: false,
autoIncrement:true,
primaryKey:true
},
firstName : {
type: DataTypes.STRING(50),
allowNull: false
},
lastName : {
type: DataTypes.STRING(50),
allowNull: false
},
dateOfBirth : {
type: DataTypes.DATE,
allowNull: false
}
});
return User;
};
儿童班:
'use strict';
module.exports = function(sequelize, DataTypes) {
const Children= sequelize.define('Children', {
id : {
type: DataTypes.INTEGER(11),
allowNull: false,
autoIncrement:true,
primaryKey:true
},
userId : {
type: DataTypes.INTEGER(11),
allowNull: true,
references : {
model : 'Users',
key:'id'
}
},
status : {
type: DataTypes.BOOLEAN,
allowNull: false,
defaulValue: false
},
firstName : {
type: DataTypes.STRING(50),
allowNull: false
},
lastName : {
type: DataTypes.STRING(50),
allowNull: false
},
dateOfBirth : {
type: DataTypes.DATE,
allowNull: false
}
});
return Children;
};
解决方案
尝试 :
let transaction;
try {
// get transaction
transaction = await sequelize.transaction();
//save here
User.build({
firstName: "John"
//other attributes
}).save().then(newUser => {
const id = newUser.id;
Children.build({
firstNames: "fsf"
userId: id // from newly created user
//other attributes
})
.save()
.then(children => console.log("svaed"))
}).catch(function(error) {
// error
});
// commit
await transaction.commit();
} catch (err) {
// Rollback transaction
if (transaction) await transaction.rollback();
}
推荐阅读
- swift - Xcode 错误未识别问题所在的代码行
- php - 如何根据给定的字符串和按下按钮时隐藏从数据库中获取信息的表行
- python - 如何在flask rest api python中获取文件的响应
- tmux - 如何从 tmux 会话中删除所有拆分窗口?
- python - 将 3d 列表从 python 传输到 Matlab
- python - 检查子弹精灵与水泥块精灵的碰撞
- reactjs - 组件库中的 Next.js 和巨型 css 文件,如何删除?
- c# - 我猜如何引用一个类?
- bash - Bash 排序顺序是否在不同的 Linux 发行版上有所不同?
- python - 如何在不需要用户代理的情况下创建 API?