[英]Sequelize get parent reference when multiple child objects are created
我正在創建一組 Sequelize model 作為下面的鏈。 創建所有子模型后,如果成功,我想將其重定向到父模型的詳細信息頁面(發票)。 問題是因為我使用了一個循環,我怎么知道所有的孩子都被正確創建來進行重定向? 在重定向代碼中,我也想訪問父 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)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.