Sequelize.JS Postgresql-如何从关联表中SUM到主表中的比较字段

时间:2017-11-26 15:28:48

标签: node.js postgresql sequelize.js has-many

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



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




1 个答案:

答案 0 :(得分:1)

对于那些可能有同样关注的人,这里有一种方法可以做到这一点。

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

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