Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
  })))
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!