Hier, meine Modelle und seine Beziehungen.Sequelize.JS Postgresql- Wie SUM aus verbundenen Tabelle zu Feld in Master-Tabelle zu vergleichen
// One to Many Relationship between receiptitems and receipts
db.Receipts.hasMany(db.ReceiptItems,{ foreignKey : 'receipt_id'});
db.ReceiptItems.belongsTo(db.Receipts,{ foreignKey : 'receipt_id'});
// One to Many Relationship between ReceiptItems and Payments
// This relation exists due to solve the problem of paying the debts later on !
db.Receipts.hasMany(db.Payments, { foreignKey : 'receipt_id' });
db.Payments.belongsTo(db.Receipts, { foreignKey : 'receipt_id' });
// One to many Relationship between Receipts and Plates
db.Plates.hasMany(db.Receipts, { foreignKey : 'plate_id' });
db.Receipts.belongsTo(db.Plates, { foreignKey : 'plate_id' });
Hier, was ich erreichen will ist, dass ich die Belege finden will, die mit dem plate_id übereinstimmt und die Belege zu finden, wo jeder seiner Summe der Zahlungen ist niedriger als die Gebühr in Höhe von die Rechnung.
// db.Op.lt bedeutet, dass "weniger als"
db.Receipts.findAll({
where : {
plate_id : result.plate_id,
fee : { [ db.Op.lt ] : db.Payments.sum('receivedPayment')}
},
include : [db.Receipts.associations.Payments,
db.Receipts.associations.ReceiptItems,
]
}).then((receiptResult)=>{
console.log("result"+JSON.stringify(receiptResult));
}).catch((receiptErr)=>{
console.log(receiptErr);
})