How to delete a record with a foreign key using sequelize

Asked

Viewed 503 times

0

I created a web application using sequelize, my model looked like this:

const Product = db.sequelize.define('product', {
    idProduct: {
        type: db.Sequelize.STRING,
        primaryKey: true,
        autoIncrement: false
    },
    name: {
        type: db.Sequelize.STRING
    },
    idCategory: {
        type: Sequelize.STRING,

        references: {
            model: Category,
            key: 'idCategory',
        }
    }
})

I can register normally by entering the id, name and id of the foreign key, but when I try to delete the record returns a Constraint error because of the foreign key.

My code to delete:

app.post('/produto', (req, res) => {
    Product.destroy({ where: { idProduct: req.body.id } }).then(() => {
        res.redirect('/produto')
    }).catch((err) => {
        res.redirect('/')
    })
})

How can I delete a record that references another table in the sequelize?

1 answer

0

You are passing primaryKey and not the foreign key, so the problem, how I imagine it will work:

Product.destroy({ where: { idCategory: req.body.id } })
.then(() => {
  res.redirect('/produto')
}).catch((err) => {
  res.redirect('/')
})

If the problem occurs because you need to delete in two tables at once, you will need to wrap it in a Sequelize Transaction or adjust the Migration so that when the deletion of a certain record occurs in one table the other will naturally apply a CASCADE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.