简体   繁体   English

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

[英]How to update a two table in single api call using sequelize.transaction in node using Sequelize

I have two tables users and company i want to update the record in "PUT" method.我有两个表用户和公司,我想以“PUT”方法更新记录。 i geting the values in attributes.我得到属性中的值。 how to update in db using sequelize in nodejs如何在nodejs中使用sequelize在db中更新

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

You need something like this to update your records, assuming userId matches your pk:假设 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()
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM