gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:23:45 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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


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

关于node.js - Sequelize.JS Postgresql- 如何从关联表求和以比较主表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47497749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com