【问题标题】:How to update row in one to many relation in Sequelize?如何在 Sequelize 中以一对多关系更新行?
【发布时间】:2021-12-23 00:49:01
【问题描述】:

我有一个与权限表以一对多关系相关的用户表(用户有很多权限),我想知道更新用户权限的干净和正确的方法。

这是我写的代码,但我觉得这不是正确的做法:

update(req, res) {
  db.sequelize
    .transaction()
    .then(t => {
        Group.findByPk(req.params.id).then(group => {
          if (!group)
            return res.status(404).send({
              error: "Ce groupe n'éxiste pas"
            });

         GroupPrivilege.destroy({
           where: { groupId: req.params.id },
           transaction: t
         }).then(resDestroy => {
           req.body.group_privileges.forEach(element => {
           element.groupId = req.params.id;
         });

        GroupPrivilege.bulkCreate(req.body.group_privileges, {
          transaction: t
        }).then(resCreatePrivileges => {
          delete req.body.group_privileges;
          console.log(req.body);
          Group.update(req.body, {
            where: { id: req.params.id },
            transaction: t
          }).then(resSave => {
            t.commit();
            return res.status(200).send("");
          });
        });
      });
    });
  })
  .catch(err => {
    t.rollback();
    return res.status(400).send(err);
  });
}

【问题讨论】:

  • 到目前为止您尝试过什么?你能告诉我们吗
  • 我试图破坏所有相关权限,使用 bulkCreate 创建新权限,然后更新组信息。

标签: express sequelize.js


【解决方案1】:

这是我写的代码,但我觉得它不是正确的方法:

 update(req, res) {
    db.sequelize
      .transaction()
      .then(t => {
        Group.findByPk(req.params.id).then(group => {
          if (!group)
            return res.status(404).send({
              error: "Ce groupe n'éxiste pas"
            });

          GroupPrivilege.destroy({
            where: { groupId: req.params.id },
            transaction: t
          }).then(resDestroy => {
            req.body.group_privileges.forEach(element => {
              element.groupId = req.params.id;
            });
            GroupPrivilege.bulkCreate(req.body.group_privileges, {
              transaction: t
            }).then(resCreatePrivileges => {
              delete req.body.group_privileges;
              console.log(req.body);
              Group.update(req.body, {
                where: { id: req.params.id },
                transaction: t
              }).then(resSave => {
                t.commit();
                return res.status(200).send("");
              });
            });
          });
        });
      })
      .catch(err => {
        t.rollback();
        return res.status(400).send(err);
      });
  }

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多