Select 加入多对多和计算一对多

Select with joining many-to-many and count one-to-many

我有两个查询,在一个地方我同时需要它们。我该如何修改第一个?

第一个(一对多):

    const server = await Server.findOne({
      where: { id },
      attributes: {
        include: [[Sequelize.fn('COUNT', Sequelize.col('users.id')), 'localUserCount']],
      },
      include: [{ model: User, attributes: [] }],
      group: ['Server.id'],
      raw: true,
    });

第二个(多对多):

    const serverWithAdmins = await Server.findOne({
      where: { id },
      include: [{ model: AdminUser, as: 'adminUserList', through: { attributes: [] } }],
    });

我需要这样的东西:

    const server = await Server.findOne({
      where: { id },
      attributes: {
        include: [[Sequelize.fn('COUNT', Sequelize.col('users.id')), 'userCount']],
      },
      include: [
        { model: User, attributes: [] },
        // New line
        { model: AdminUser, as: 'adminUserList', through: { attributes: [] } }
      ],
      group: ['Server.id'],
      raw: true,
    });

但是在最后一个查询中我得到了这样的错误:

"column \"adminUserList.id\" must appear in the GROUP BY clause or be used in an aggregate function"

我想将 AdminUser 属性添加到 group 或添加 attributes,但我仍然无法为 Server 获取 AdminUser 的数组就像在第二个查询中一样。是否可以使用聚合函数 COUNT 并在一个查询中加入另一个关系?

您需要使用子查询将 Sequelize.fn 转换为 Sequelize.literal,并从 include 选项和 group 选项中删除 User

const server = await Server.findOne({
      where: { id },
      attributes: {
        include: [
         [Sequelize.literal('(SELECT COUNT(*) FROM Users where Users.serverId=Server.id)'), 'userCount']
         ],
      },
      include: [
        { model: AdminUser, as: 'adminUserList', through: { attributes: [] } }
      ],
    });