Mysql Sequelize从关联表中获取列的总和

Mysql Sequelize从关联表中获取列的总和,mysql,sequelize.js,Mysql,Sequelize.js,我有两张桌子 CustomerAccount和CustomerAccountService 它们以以下方式相互关联: CustomerAccount.hasMany(CustomerAccountService, { foreignKey: 'account_uuid' }); CustomerAccountService.belongsTo(CustomerAccount, { as: 'account', foreignKey: 'account_uuid' });

我有两张桌子

CustomerAccount
CustomerAccountService

它们以以下方式相互关联:

CustomerAccount.hasMany(CustomerAccountService, {
    foreignKey: 'account_uuid'
});

CustomerAccountService.belongsTo(CustomerAccount, {
    as: 'account',
    foreignKey: 'account_uuid'
});
CustomerAccountService有两列,分别为发票金额和核心金额

我想获得所有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\u 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'
        }
    );

您的模型定义将表名设置为
customer\u accounts\u services
,但您将
CustomerAccountService
的模型名传递给
Sequelize.col()
,该模型名不存在,因此您会得到有关缺少列的错误

Sequelize.col()
中更新查询以使用正确的表名


您可以包括您的模式或模型定义吗?是否存在
invoice\u amount
字段,或者是数据库中的
invoiceAmount
?您还可以向查询中添加
logging:true
,以记录SQL,以便检查。是的,发票金额和核心金额字段确实存在于模型定义中。谢谢-现在发布答案,明白了。我的印象是我们应该使用模型。谢谢你的帮助。@codeinprogress通常你应该这样做,但它不是100%一致的。很高兴你成功了!另一个注意事项(与上面的问题不同)-当我尝试在页面上显示totalInvoiceAmount时(使用手柄,它不会显示)。知道为什么会发生这种情况吗?它可能没有映射到模型属性,因此您必须从“数据值”-
result.getDataValue('totalInvoiceAmount')
访问它。您还可以设置映射到数据值的虚拟字段,然后可以直接访问它,但这取决于是否值得污染模型属性。。。
[Sequelize.fn('SUM', Sequelize.col('customer_accounts_services.invoice_amount')), 'totalInvoiceAmount'],
[Sequelize.fn('SUM', Sequelize.col('customer_accounts_services.core_amount')), 'totalCoreAmount']