【问题标题】:Get the count of Associated tables using sequelize使用 sequelize 获取关联表的计数
【发布时间】:2022-01-08 20:48:01
【问题描述】:

在我的案例中,帐户是一个父表帐户,它有许多成员,一个帐户有许多组,帐户有许多角色。因此,我尝试按如下方式对每个表进行计数。

  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));

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

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    您要么需要将此查询分成三个以分别计算每个子模型记录计数,要么删除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"],
      ]
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2016-10-15
      • 2016-10-24
      • 2021-05-27
      • 1970-01-01
      • 2017-10-15
      相关资源
      最近更新 更多