Libin C Jacob
Libin C Jacob

Reputation: 1138

Sequelize destroy from multiple tables

I would like to delete records from multiple table one after another. Under a single router, how could I call the following destroy functions one after another

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

Upvotes: 1

Views: 968

Answers (1)

goto
goto

Reputation: 4445

When you say

Under a single router

I am assuming you have a setup similar to a Node.js and Express.js application where your route and handler look like the following:

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

In this case, you could do the following:

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)

This way, all deletion calls get completed before you return the success response.


Alternatively, if you need to your call need to be sequential, then you could do the following:

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)

Here's an example - jsbin.com

Upvotes: 2

Related Questions