续集一对多关联更新不起作用



我的两个模型是这样连接的:

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

我正在尝试更新DebitInvoice,同时这样做,我还需要删除以前的DebitInvoiceProduct行,并添加新的。这就是我使用onUpdate: 'CASCADE'的原因。我正在尝试使用这个代码:

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

我可以更新DebitInvoice字段,但DebitInvoiceProduct没有任何变化

我哪里做错了,或者我应该怎么做才能得到我需要的?

update没有include选项,因此您要么需要为每个DebitInvoice模型实例调用setDebitInvoiceProducts,要么在DebitInvoiceProducts上调用destroycreate:

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)
}

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
  })))
}

相关内容

  • 没有找到相关文章

最新更新