【问题标题】:sequelize findall with count every relation child for each parent用计算每个父母的每个关系孩子来对 findall 进行续集
【发布时间】: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


【解决方案1】:

这对于 1:m 关联应该非常有效。让您为每个父母计算孩子。但是,由于某种原因,这不适用于多个“包含”。所以注意!!!:

  1. 试图计算孙子会破坏整个查询
  2. 试图获取孩子的属性会破坏整个查询

续集:5.21.11

await ClientModel.findAll({
  include: [
    {
      as: 'statistic',
      model: StatisticModel,
      attributes: [], // empty array is important here!
     },
  ],
  attributes: [
    'id', [Sequelize.fn("COUNT", Sequelize.col("statistic.id")), "total"] 
  ],
  group : ['ClientModel.id'], // group only by parent.id here!
});

【讨论】:

    【解决方案2】:

    必须根据this issue对父模型进行聚合

    为您的用例尝试以下代码

      await ClientModel.findAll({
        attributes: [
          "username",
          [Sequelize.fn("COUNT", Sequelize.col("statistic.id")), "total"],
        ],
        include: [
          {
            as: "statistic",
            model: StatisticModel,
            attributes: [],
          },
        ],
        group: ["ClientModel.id"],
      });
    

    续集 >= 3.0.1

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 2015-08-10
      • 2016-11-25
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多