2017-11-26 13 views
0

ここでは、私のモデルとその関係。ここでSequelize.JS Postgresql - 関連テーブルからSUMテーブルを比較する方法

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

、私が達成したいことは、私はplate_idと一致する領収書を見つけ、支払いのその合計のそれぞれが、の料金、次に低い領収書を見つけたいということですレシート。

// db.Op.ltは、これを行う一つの方法のための方法ここでは、

同じ懸念を持っていることが人のために

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

答えて

0

"より少ない" ということを意味します。

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...)

あなたはそれを試した後、私にフィードバックを送ること自由に感じなさい。

関連する問題