Sequelize.JS Postgresql-如何从关联 table 求和以比较主 table 中的字段

Sequelize.JS Postgresql- How to SUM from associated table to compare field in master table

在这里,我的模型及其关系。

// 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表示"less than"

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

对于那些可能有同样问题的人,这里是一种方法。

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

尝试后请随时向我发送反馈。