我有两个桌子
CustomerAccount
和CustomerAccountService
它们通过以下方式关联:
CustomerAccount.hasMany(CustomerAccountService, {
foreignKey: 'account_uuid'
});
CustomerAccountService.belongsTo(CustomerAccount, {
as: 'account',
foreignKey: 'account_uuid'
});
CustomerAccountService有两列,分别名为invoice_amount和core_amount。
我想获取所有CustomerAccount的列表,并在该列表中显示其子项CustomerAccountService记录的所有发票金额和所有核心金额的总和。
这是我正在尝试的查询:
CustomerAccount.findAll({
attributes: [
'uuid',
'account_name',
'account_number',
'emergency_pay',
[Sequelize.fn('SUM', Sequelize.col('CustomerAccountService.invoice_amount')), 'totalInvoiceAmount'],
[Sequelize.fn('SUM', Sequelize.col('CustomerAccountService.core_amount')), 'totalCoreAmount']
],
include: [
{
model: CustomerAccountService,
attributes: []
}
],
group: ['CustomerAccount.uuid']
}).then(...);
但是它抛出一个错误提示
未处理的拒绝SequelizeDatabaseError:未知列 “字段列表”中的“ CustomerAccountService.invoice_amount”
如何从关联表中获得两列的总和?
CustomerAccountService的模型定义为:
return sequelize.define(
'customer_accounts_services',
{
uuid: {
type: type.STRING,
primaryKey: true,
autoIncrement: false
},
account_uuid: type.STRING,
account_number: type.STRING,
account_type: type.STRING,
payment_type: type.STRING,
service_type: type.STRING,
date: type.DATEONLY,
description: type.TEXT,
invoice_amount: type.DECIMAL(10,2),
core_amount: type.DECIMAL(10,2),
paid: type.BOOLEAN
},
{
timestamps: false,
underscored: true,
tableName: 'customer_accounts_services'
}
);
答案 0 :(得分:1)
您的模型定义将表名称设置为customer_accounts_services
,但是您将CustomerAccountService
的模型名称传递给Sequelize.col()
,该名称不存在,因此您会收到有关缺少列。
更新查询以使用Sequelize.col()
中正确的表名。
[Sequelize.fn('SUM', Sequelize.col('customer_accounts_services.invoice_amount')), 'totalInvoiceAmount'],
[Sequelize.fn('SUM', Sequelize.col('customer_accounts_services.core_amount')), 'totalCoreAmount']