我有以下功能,当传递新的用户数据时,该功能有效。它将对象和子对象成功保存到mysql表中。但是考虑到我正在使用sequelize事务,一旦保存到数据库后,我该如何返回对象。
static async add(user) {
let transaction;
try {
// get transaction
transaction = await models.sequelize.transaction();
// *****how to return the newly created user *****************************************
models.User.create(user).then(newUser => {
const id = newUser.id;
//save address
if(user.address){
address.userId = id;
models.Address.create(address);
}
}).catch(error => {
throw error;
});
await transaction.commit();
} catch (error) {
console.log(error);
// Rollback transaction
if (transaction) await transaction.rollback();
throw error;
}
}
答案 0 :(得分:1)
尝试创建自动交易,使用await并在模型的transaction
函数中指示create
:
static async add(user) {
try {
const createdUser = await models.sequelize.transaction(transaction => {
const newUser = await models.User.create(user, { transaction })
//save address
if(user.address){
address.userId = newUser.id;
await models.Address.create(address, { transaction });
}
return newUser;
});
// if you are here it means transaction already commited
return createdUser;
} catch (error) {
// if you are here it means transaction already rolled back
console.log(error);
throw error;
}
}