我正在创建一组 Sequelize 模型作为下面的链。创建所有子模型后,如果成功,我想将其重定向到父模型(发票)的详细信息页面。问题是因为我使用了一个循环,我怎么知道所有的 child 都是正确创建的以进行重定向?在重定向代码中,我也想访问父 ID。
Invoice.create({
//set parent properties
}).then(invoice => { //update company id
return Company.findOne({where: {id: id}}).then(company => {
//console.log('setting the company...')
return invoice.setCompany(company).then(invoice => {return invoice})
})
}).then(invoice => { //create order items
orderItems.each((i, v) => {
invoice.createOrderItem({
}).then(orderItem => {
return Product.findOne({where: {id: v.companyId).then(product => {
//console.log('setting the product...')
return orderItem.setProduct(product).then(orderItem => {return orderItem})
})
}).then(orderItem => {
return Unit.findOne({where: {id: v.unitId}).then(unit => {
//console.log('setting the unit...')
return orderItem.setUnit(unit).then(orderItem => {return invoice})
})
}).then(invoice => {
//console.log('returning invoice: ' + invoice)
return invoice
}).catch(errOI => {
console.log('Error while creating order items: ' + errOI)
})
})
}).then(invoice => {
//redirect to detail page
console.log('I: ' + invoice)
}).catch(errI => {
console.log('Error while creating invoice: ' + errI)
})
最佳答案
function createChild(v) {
return new Promise((resolve, reject) => {
invoice.createOrderItem({})
.then(orderItem => {
return Product.findOne({where: {id: v.companyId).then(product => {
//console.log('setting the product...')
return orderItem.setProduct(product).then(orderItem => {return orderItem})
})
})
.then(orderItem => {
return Unit.findOne({where: {id: v.unitId}).then(unit => {
//console.log('setting the unit...')
return orderItem.setUnit(unit).then(orderItem => {return invoice})
})
})
.then(invoice => {
//console.log('returning invoice: ' + invoice)
return invoice;
})
.then(invoice => {
resolve();
})
.catch(errOI => {
console.log('Error while creating order items: ' + errOI)
reject();
})
});
}
Invoice.create({
//set parent properties
}).then(invoice => { //update company id
return Company.findOne({where: {id: id}}).then(company => {
//console.log('setting the company...')
return invoice.setCompany(company).then(invoice => {return invoice})
})
}).then(invoice => { //create order items
return orderItems.map(v => {
return createChild(v);
})
}).then(promises => {
return Promise.all(promises)
.then(done => {
// direct the page
})
})
}).catch(errI => {
console.log('Error while creating invoice: ' + errI)
})
关于javascript - 创建多个子对象时,Sequelize 获取父引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61765398/