我的两个模型是这样连接的:
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
上调用destroy
和create
:
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
})))
}