node.js - 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_id
and对它进行了分组id
,但是如果我删除id
它会导致这样的错误
选择列表中的“ProductBuy.id”列无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。
我怎样才能做到这一点。谢谢
解决方案
推荐阅读
- excel - PowerBI、筛选、搜索并根据结果 DAX 创建新表
- c++ - 用于数组数组的 opengl glUniform (ARB_arrays_of_arrays)
- markdown - 带有 Gravizo 的 Markdown BitBucket wiki 中的 PlantUML 图像
- java - Android:在islatedProcess中获取空值
- jquery - 如何使用jquery在多个数组中过滤长度大于零的数组?
- powerbi - Power BI - 如何计算具有不同筛选器的两个相同集合中的重复项
- php - Laravel - 断言没有软删除?逆?- Laravel 测试
- math - python中逐元素张量乘法
- docker - Jenkins Artifactory 插件
- r - 在 R 中有效地查找人口数据中的中位数