首页 > 解决方案 > Sequelize COUNT 在 INCLUDE 关联返回错误聚合函数或 GROUP BY 子句

问题描述

我在我的 ExpressJS 中使用Sequelize和 SQL Server。我有两个名为 PersonalInfo 和 ProductBuy 的表,它有关系 PersonalInfo hasMany ProductBuy。

这是我的模型的关联:

个人信息.js

PersonalInfo.hasMany(models.ProductBuy, {
   foreignKey: 'member_id',
   sourceKey: 'id'
});        

ProductBuy.js

ProductBuy.belongsTo(models.PersonalInfo, {
   foreignKey: 'member_id',
   targetKey: 'id'
});

我想获得每个用户的ProductBuy计数。预期结果:

{
    "data": [
        {
            "id": 1,
            "ProductBuys": [
                {
                    "total_active": 3
                }
             ]
        },
        {
            "id": 2,
            "ProductBuys": [
                {
                    "total_active": 1
                }
             ]
        }
    ]
}

这是我在控制器中的功能:

getAll: function (req, res) {
    PersonalInfo.findAll({
        attributes: ['id'],
        include: [
            {
                model: ProductBuy,
                attributes: [
                    [Sequelize.fn('COUNT', Sequelize.col('member_id')), 'total_active']
                ],
                separate:true,
                where: {
                    status: ['Aktif', 'Expired']
                },
                group:['member_id', 'id']
            }
        ],
    }).then(value => {
        responseUtil.success(res, value)
    })
}

但是,这就是我得到的

{
    "data": [
        {
            "id": 1,
            "ProductBuys": [
                {
                    "total_active": 1
                },
                {
                    "total_active": 1
                },
                {
                    "total_active": 1
                }
             ]
        },
        {
            "id": 2,
            "ProductBuys": [
                {
                    "total_active": 1
                }
             ]
        }
    ]
}

我认为发生这种情况是因为我通过member_idand对它进行了分组id,但是如果我删除id它会导致这样的错误

选择列表中的“ProductBuy.id”列无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

我怎样才能做到这一点。谢谢

标签: node.jssql-serversequelize.js

解决方案


推荐阅读