Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda