我用 ExpressJs 和 Sequelize 和 SQL Server 构建了一个应用程序的后端。
我有两个表,分别称为 User 和 Order。一个用户有很多订单。
我想列出所有 用户 包括他们的 订单 (作为计数)。
这是我的代码:
User.findAll({
attributes: ['id'],
include: [
{
model: ProductBuy,
attributes: [
[Sequelize.fn('COUNT', Sequelize.col('Order.member_id')), 'total_active']
],
where: {status: ['Active', 'Expired']}
}
],
})
但它给了我一个错误
Column 'User.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我不明白这一点,因为我还没有使用过组。
但是如果我添加一个分组
group:['Order.member_id', 'User.id', 'Order.id']
它成功获取数据,但不计算订单,它像这样在每个用户中一一显示每个订单:
{
"id": 4,
"orders": [
{
"total_active": 1
},
{
"total_active": 1
}
]
},
我想说的是用户 A 有 4 个 total_active,用户 B 有 6 个 total_active 那样
我如何实现这一目标?
Table Structure
User
| id | name |
| 1 | Andrew |
| 2 | Bruce |
命令
| id | user_id | status |
| 1 | 1 | Active |
| 2 | 1 | Expired |
| 3 | 2 | Active |
预期结果
{
"data": [
{
"id": 1,
"Orders": [
{
"total_active": 2
}
]
},
{
"id": 2,
"Orders": [
{
"total_active": 1
}
]
},
]
}
Screenshot result
最佳答案
我认为您可以从 ProductBuy
中取出属性字段并像这样使用它:
User.findAll({
attributes: [
'id'
[Sequelize.fn('COUNT', Sequelize.col('Order.member_id')), 'total_active'] // <--- HERE
],
include: [
{
model: ProductBuy,
where: {status: ['Active', 'Expired']}
}
],
group:['User.id', 'Order.id']
})
NOTE :
If its counting duplicate records you can also use
DISTINCT
like this
[Sequelize.fn('COUNT', Sequelize.fn('DISTINCT',Sequelize.col('Order.member_id'))), 'total_active']
关于node.js - 即使我没有使用 GROUP BY,SQL Server 的 Sequelize 也会返回错误聚合函数或 GROUP BY 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785592/