Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda