【问题标题】:Sequelize destroy from multiple tables从多个表中续集销毁
【发布时间】:2019-08-03 12:07:36
【问题描述】:

我想一个接一个地从多个表中删除记录。单路由器下,怎么会一个接一个地调用下面的destroy函数

function deleteFromTable1(param1, transaction) {
  return table1_model.destroy({
    where: { param1 },
    transaction
  });
}

function deleteFromTable2(param1, transaction) {
  return table2_model.destroy({
    where: { param1 },
    transaction
  });
}

function deleteFromTable3(param1, transaction) {
  return table2_model.destroy({
    where: { param1 },
    transaction
  });
}

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    当你说

    在单个路由器下

    我假设您的设置类似于 Node.jsExpress.js 应用程序,其中您的路由和处理程序如下所示:

    app.post('/delete', function (req, res) {
      // delete some items from database
    })
    

    在这种情况下,您可以执行以下操作:

    function deleteItems(req, res) {
      // since Sequelize `destroy` calls return promises, 
      // you can just wrap all of them in `Promise.all`
      // and "wait" for all of them to `resolve` (complete)
    
      const handleSuccessfulDeletion = () => {
        res.status(200).json({ 
          status: 200, 
          message: 'OK' 
        })
      }
      const handleError = (error) => {
        // ...
      }
    
      Promise.all([
        deleteFromTable1(param1, transaction),
        deleteFromTable2(param1, transaction),
        deleteFromTable3(param1, transaction)
      ])
        .then(handleSuccessfulDeletion)
        .catch(handleError)
    }
    app.post('/delete', deleteItems)
    

    这样,所有删除调用都会在您返回 success 响应之前完成。


    或者,如果您需要按顺序调用,则可以执行以下操作:

    function deleteItems(req, res) {
      const handleSuccessfulDeletion = () => {
        // ...
      }
      const handleError = (error) => {
        // ...
      }
    
      deleteFromTable1(param1, transaction)
        .then(() => deleteFromTable2(param1, transaction))
        .then(() => deleteFromTable3(param1, transaction))
        .then(handleSuccessfulDeletion)
        .catch(handleError)
    }
    app.post('/delete', deleteItems)
    

    这是一个例子 - jsbin.com

    【讨论】:

    • 我已经尝试过承诺。在我的情况下,表之间存在一些依赖关系。所以我需要顺序执行它
    • 第二种方法呢?我已经编辑了我的答案
    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2014-05-05
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    相关资源
    最近更新 更多