Search code examples
node.jsexpressmodelsequelize.js

Sequelize One to Many Association Update won't work


This is how my two models are connected:

DebitInvoice.hasMany(DebitInvoiceProduct, {
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE',
    foreignKey: 'invoice_serial'
});
DebitInvoiceProduct.belongsTo(DebitInvoice,{
    foreignKey: 'serial'
});

I am trying to update DebitInvoice and while doing so I also need to delete previous DebitInvoiceProduct rows and add new ones. That is why I am using onUpdate: 'CASCADE'. I am trying with this code:

const result = await DebitInvoice.update({
    invoice_for: 'data',
    invoice_date: 'data',
    /* other fields */
    DebitInvoiceProducts: productList,
},{
    where: {serial: 'data'}
},
    include: [DebitInvoiceProduct]
);

I can update DebitInvoice fields but nothing happening at DebitInvoiceProduct

Where I am doing wrong or What should I do to get what I needed?


Solution

  • update does not have include option so you either need to call setDebitInvoiceProducts for each DebitInvoice model instance or call destroy and create on DebitInvoiceProducts:

    const invoices = await DebitInvoice.findAll({
        where: {serial: 'data'}
    });
    for (const invoice of invoices) {
      const invoiceProducts = productList.filter(x => <here are conditions to get product list for a certain invoice>)
      await invoice.setDebitInvoiceProducts(invoiceProducts)
    }
    

    OR

    const invoices = await DebitInvoice.findAll({
        where: {serial: 'data'}
    });
    await DebitInvoiceProducts.destroy({
      where: {
        invoiceId: {
          [Op.in]: invoices.map(x => x.id)
        }
      }
    })
    for (const invoice of invoices) {
      await DebitInvoiceProducts.bulkCreate(productList.map(x => ({
        productId: x.id,
        invoiceId: invoice.id
      })))
    }