2017-11-26 2 views
0

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

Antwort

0

Für diejenigen, die gleiche Sorge haben, hier die Methode für eine Art und Weise, dies zu tun.

db.Receipts.findAll({ 
 
    group: ['Receipts.receipt_id', 'ReceiptFees->User.user_id', 'ReceiptPayments->User.user_id'], 
 
    attributes: [ 
 
     [db.sequelize.fn('SUM', db.sequelize.col('ReceiptFees.fee')), 'totalFee'], 
 
     [db.sequelize.fn('SUM', db.sequelize.col('ReceiptPayments.receivedPayment')), 'totalPayment'] 
 
    ], 
 
    include: [ 
 
     { 
 
     model: db.ReceiptFees, 
 
     attributes: [], 
 
     include: [ 
 
      { association: db.ReceiptFees.associations.User }, 
 
     ] 
 
     }, 
 
     { 
 
     model: db.ReceiptPayments, 
 
     attributes: [], 
 
     include: [ 
 
      { association: db.ReceiptPayments.associations.User }, 
 
     ] 
 
     } 
 
    ], 
 
    }).then(res=> // do your work...)

, nachdem Sie versuchen, dass Sie kann mir ein Feedback zu senden.

Verwandte Themen