我在PostgreSQL数据库上有两个表,合同和付款。一份合同完成了多次付款。
我有以下两个模型:
module.exports = function(sequelize, DataTypes) { var contracts = sequelize.define('contracts', { id: { type: DataTypes.INTEGER, autoIncrement: true } }, { createdAt: false, updatedAt: false, classMethods: { associate: function(models) { contracts.hasMany(models.payments, { foreignKey: 'contract_id' }); } } }); return contracts; }; module.exports = function(sequelize, DataTypes) { var payments = sequelize.define('payments', { id: { type: DataTypes.INTEGER, autoIncrement: true }, contract_id: { type: DataTypes.INTEGER, }, payment_amount: DataTypes.INTEGER, }, { classMethods: { associate: function(models) { payments.belongsTo(models.contracts, { foreignKey: 'contract_id' }); } } }); return payments; };
我想对每个合同的所有付款进行汇总,并使用以下功能:
models.contracts.findAll({ attributes: [ 'id' ], include: [ { model: models.payments, attributes: [[models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']] } ], group: ['contracts.id'] })
但它生成以下查询:
SELECT "contracts"."id", "payments"."id" AS "payments.id", sum("payments"."payment_amount") AS "payments.total_cost" FROM "contracts" AS "contracts" LEFT OUTER JOIN "payments" AS "payments" ON "contracts"."id" = "payments"."contract_id" GROUP BY "contracts"."id";
我不要求选择payments.id,因为我必须将其包括在我的汇总或按功能分组中,如错误消息中所述:
可能未处理的SequelizeDatabaseError:错误:列“ payments.id”必须出现在GROUP BY子句中或在聚合函数中使用
我在这里想念什么吗?我正在关注这个答案,但是即使到那里我也不明白SQL请求如何有效。
此问题已在Sequelize 3.0.1中修复,必须使用以下命令排除包含模型的主键:
attributes: []
并且必须在主模型上完成聚合(此github问题中的信息)。
因此,对于我的用例,代码如下
models.contracts.findAll({ attributes: ['id', [models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']], include: [ { model: models.payments, attributes: [] } ], group: ['contracts.id'] })