使用 sequelize 获取关联表的计数

Get the count of Associated tables using sequelize

在我的案例中,帐户是父级 table 帐户有很多成员,一个帐户有很多组,帐户有很多角色。所以我尝试按如下方式计算每个 table。

  Account.findAll({
    subQuery: false, 

    where: {id: id},

    attributes: {
        include: ['*',
            [Sequelize.fn("COUNT", Sequelize.col("Members.id")), "usersCount"],
            [Sequelize.fn("COUNT", Sequelize.col("Groups.id")), "groupsCount"],
            [Sequelize.fn("COUNT", Sequelize.col("Roles.id")), "rolesCount"]]
    },
    include: [
        {
            model: Member, attributes: [], where: {accountId: id}
        },
        {
            model: Group, attributes: [], where: {accountId: id}
        },
        {
            model: Role, attributes: [], where: {accountId: id}
        }
    ],
    group: ['Account.id']
})
    .then(data => {
        let result = data.map(item => accountObj(item));
        return next(null, result[0]);
    })
    .catch(err => dbHelper.handleError(err, next));

它给我的计数不正确。还尝试了我在堆栈溢出时发现的各种其他选项。但没有找到上述查询的任何解决方案。

您需要将此查询分成三个查询以分别计算每个子模型记录数,或者删除 includegroup 选项并将 Sequelize.fn 替换为 Sequelize.literal使用子查询来计算子记录。

Account.findAll({
    where: {id: id},
    attributes: {
        include: ['*',
  [Sequelize.literal("(SELECT COUNT(*) from members as m where m.account_id=account.id)", "usersCount"],
  [Sequelize.literal("(SELECT COUNT(*) from groups as g where g.account_id=account.id)", "groupsCount"],
  [Sequelize.literal("(SELECT COUNT(*) from roles as r where r.account_id=account.id)", "rolesCount"],
  ]
    }
})