mysql 在Sequelize中计数多个关联模型

oug3syen  于 2023-02-18  发布在  Mysql
关注(0)|答案(1)|浏览(134)

我定义了3个模型,公司,项目和用户。公司有许多项目和用户,所以项目和用户有一个公司。
我面临的问题是,当我试图计算一家公司有多少用户和项目时,我得到了错误的结果,不知何故,查询多个关联是在修改彼此的值。
这是模型关联:

CompaniesModel.hasMany(AppUsersModel)
    AppUsersModel.belongsTo(CompaniesModel)

    CompaniesModel.hasMany(ProjectsModel)
    ProjectsModel.belongsTo(CompaniesModel)

这是我尝试查询每个公司的用户和项目计数的地方:

const companiesInfo = await models.companies.findAll({
        attributes: {
            include: [
                [sequelize.fn("COUNT", sequelize.col("projects.id")), "projectsCount"],
                [sequelize.fn("COUNT", sequelize.col("app_users.id")), "usersCount"],
            ],
        },
        include: [
            { model: models.projects, attributes: [] },
            { model: models.app_users, attributes: [] },
        ],
        group: ['companies.id']
    })

生成的SQL查询:

SELECT `companies`.`id`, COUNT(`projects`.`id`) AS `projectsCount`, COUNT(`app_users`.`id`) AS `usersCount` FROM `companies` AS `companies` LEFT OUTER JOIN `projects` AS `projects` ON `companies`.`id` = `projects`.`companyId` LEFT OUTER JOIN `app_users` AS `app_users` ON `companies`.`id` = `app_users`.`companyId` GROUP BY `companies`.`id`

使用这个查询,我希望得到一系列这样的公司:

[
    {name: companyX, usersCount: 1, projectsCount: 2},
    {name: companyY, usersCount: 5, projectsCount: 1},
    ...
]

但我得到的几乎是我想要的,但由于某些原因,价值观正在相互相乘,例如:

[
    {name: companyX, usersCount: 2, projectsCount: 2},
    {name: companyY, usersCount: 5, projectsCount: 5},
    ...
]

这是我得到的事件,虽然companyX只有1个用户,companyY只有1个项目,但在我看来,在companyX的情况下,usersCount乘以projectsCount。
例如,如果companyX有2个用户和2个项目,我将得到以下结果:

[
    {name: companyX, usersCount: 4, projectsCount: 4},
    ...
]

我将不胜感激的任何洞察力,以解决这一问题。

bwntbbo3

bwntbbo31#

如果在同一查询中对2列进行计数,则需要非重复计数。

include: [
    [sequelize.fn("COUNT", sequelize.fn("DISTINCT", sequelize.col("projects.id"))), "projectsCount"],
    [sequelize.fn("COUNT", sequelize.fn("DISTINCT", sequelize.col("app_users.id"))), "usersCount"],
],

相关问题