【发布时间】:2020-03-19 07:11:32
【问题描述】:
感谢您的回答。
我使用nodejs/sequelize/mysql
这是我的问题:
我有这样的表客户端:
id username age name
----------------------
12 seveun 25 john |
----------------------
10 superlol 12 johny |
----------------------
表客户端与统计表有一对多的关系
统计表如下所示:
id gain profit clientId
-------------------------
12 22 25 12 |
-------------------------
10 34 12 12 |
-------------------------
10 34 12 10 |
-------------------------
我想要这个结果:
{
client: [
{
'username': 'seveun',
'statistic': [total: 2]
},
{
'username': 'superlol'
'statistic': [total: 1]
}
]
}
我测试了这个续集代码:
await ClientModel.findAll({
include: [
{
as: 'statistic',
model: StatisticModel,
attributes: [
[[Sequelize.fn("COUNT", Sequelize.col("statistic.id")), "total"]]
],
},
],
});
但是计数,计数每个统计,而不是每个父母的统计
我的结果是:
client: [
{
'username': 'seveun',
'statistic': [total: 3]
}
非常感谢您的帮助
【问题讨论】:
-
没有多对多抱歉,只有一对多
-
正确编辑问题文本。
-
如果金额是在整个表格中计算的,那么您必须告诉您需要对用户名进行分组。 IE。添加
group: ['username']。 -
这能回答你的问题吗? How does group by works in sequelize?
-
感谢您的回答,但不是因为结果将是
client: [ [{ 'username': 'seveun', 'statistic': [total: 3] }, { username': 'superlol', 'statistic': [total: 3]}]计数将计算每个统计数据
标签: mysql node.js sequelize.js