繁体   English   中英

在续集上使用 COUNT 聚合 function 添加不需要的 id 字段

[英]Using COUNT aggregate function on sequelize adding unwanted id field

我正在尝试使用 sequelize 6.21.6对相关模型进行 COUNT 获取每个类别下的工作总数。

我的 model 看起来像:

models.Sector.hasMany(models.Category, {
   foreignKey: 'sectorId',
   as: 'Categories',
});

models.Category.hasMany(models.Job, {
   foreignKey: 'categoryId',
   as: 'Jobs',
});

我正在使用 COUNT 运行此查询:

const getSectorsCategories = async () => {
  const sectors = await Sector.findAll({
    attributes: [
      'name'
    ],
    include: [
      {
        model: Category,
        as: 'Categories',
        attributes: ['name', 'sectorId',
          [sequelize.fn('COUNT', sequelize.col('Categories.Jobs.id')), 'jobCount']
        ],
        include: [
          {
            model: Job,
            as: 'Jobs',
            attributes: ['title', 'categoryId'],
          },
        ],
      },
    ],
    group: ['Sector.id', 'Categories.id'],
  },);
  return sectors;
};

使用以下 SQL:

Executing (default): 
SELECT 
  "Sector"."id", 
  "Sector"."name", 
  "Categories"."id" AS "Categories.id", 
  "Categories"."name" AS "Categories.name", 
  "Categories"."sectorId" AS "Categories.sectorId", 
  COUNT("Categories->Jobs"."id") AS "Categories.jobCount", 
  "Categories->Jobs"."id" AS "Categories.Jobs.id", 
  "Categories->Jobs"."title" AS "Categories.Jobs.title", 
  "Categories->Jobs"."categoryId" AS "Categories.Jobs.categoryId" 
FROM 
  "Sectors" AS "Sector" 
  LEFT OUTER JOIN "Categories" AS "Categories" ON "Sector"."id" = "Categories"."sectorId" 
  LEFT OUTER JOIN "Jobs" AS "Categories->Jobs" ON "Categories"."id" = "Categories->Jobs"."categoryId" 
GROUP BY 
  "Sector"."id", 
  "Categories"."id", 
  "Categories->Jobs"."id";

您注意到此字段是由 sequelize 自动添加的: "Categories->Jobs"."id" AS "Categories.Jobs.id"

现在产生此错误:

"error": "column \"Categories->Jobs.id\" must appear in the GROUP BY clause or be used in an aggregate function"

似乎消除此错误的唯一方法是将空属性数组传递给 Jobs:

include: [
   {
     model: Job,
     as: 'Jobs',
     attributes: [],
   },
]

现在聚合 function COUNT可以按预期工作,但我没有任何我想要的工作属性列表。

这种全有或全无的方法有什么解决方法吗?

您可以尝试使用 window function。

const sectors = await Sector.findAll({
  attributes: [
    'name'
  ],
  include: [
    {
      model: Category,
      as: 'Categories',
      attributes: ['name', 'sectorId',
        [sequelize.literal('COUNT("Categories->Jobs"."id") OVER (PARTITION BY "Sector"."id", "Categories"."id")'), 'jobCount']
      ],
      include: [
        {
          model: Job,
          as: 'Jobs',
          attributes: ['title', 'categoryId'],
        },
      ],
    },
  ],
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM