如何使用sequelize在节点中使用sequelize.transaction在单个api调用中更新两个表



我有两个表,用户和公司我想更新"PUT";方法我获取属性中的值。如何在nodejs 中使用sequelize在数据库中更新

function updateUserProfileById(userId, attributes) {
return sequelize.transaction(() =>
User.update({
alternate_email_id: attributes.Alternate_Email_Id,
alternate_mobile_no: attributes.Alternate_Mobile_No,
}).then((updateUser) => {
const company = {
industry_type: attributes.industry,
address: attributes.address,
pincode: attributes.pincode,
};
return Company.update(company).then(() => {
return updateUser;
});
})
);
}

假设userId与你的pk:匹配,你需要这样的东西来更新你的记录

function updateUserProfileById(userId, attributes) {
return sequelize.transaction().then(transaction) => {
return User.findByPk(userId)
}).then(aUser => {
aUser.alternate_email_id = attributes.Alternate_Email_Id
aUser.alternate_mobile_no = attributes.Alternate_Mobile_No
return aUser.save({transaction: transaction})
}).then((updateUser) => {
return Company.findByPk(theIdOfYourCompany)
}).then(aCompany => {
aCompany.address = attributes.address
aCompany.pincode = attributes.pincode
return aCompany.save({transaction: transaction})
}).then(updateCompany => {
return transaction.commit()
}).catch(error => {
return transaction.rollback()
})
}

最新更新