title: Sequelize.JS Postgresql- How to SUM from associated table to compare field in master table
body: <p>Here, my models and its relations.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// 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' });</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here, what I want to achieve is that I want to find the receipts that matches with the plate_id and find the receipts where each of its sum of payments are lower then the fee of the receipt.</p>
  
  <p>// db.Op.lt means that "less than"</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>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)=&gt;{
          console.log("result"+JSON.stringify(receiptResult));
        }).catch((receiptErr)=&gt;{
          console.log(receiptErr);
        })</code></pre>
  </div>
  </div>
  </p>