Sequelize One to Many Association Update 不起作用

Sequelize One to Many Association Update won't work

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

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 或调用 destroycreateDebitInvoiceProducts 上:

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