简体   繁体   English

使用 Sequelize 多次加入同一个表

[英]Joining to the same table multiple times with Sequelize

I am trying to write a query with that would roughly do:我正在尝试编写一个大致可以做的查询:

SELECT Challenge.id, Challenge.name, count(AcceptedChallenge.userId) AS attempts, count(a.met) AS met, count(b.active) AS active, count(c.id) AS WHOLE
FROM Challange 
LEFT JOIN AcceptedChallenge ON Challenge.id = AcceptedChallenge.challengeId,
LEFT JOIN AcceptedChallenge AS a ON Challenge.id = a.challengeId
LEFT JOIN AcceptedChallenge AS b ON Challenge.id = b.challengeId
LEFT JOIN AcceptedChallenge AS c ON Challenge.id = c.challengeId
WHERE a.met = true 
AND b.userId = id and b.active = true
AND c.userId = id;

Tried multiple versions, including the below:尝试了多个版本,包括以下:

const Sequelize = require('sequelize');
const ChallengeController = async ({ user: { id } }) => {
  const challenges = await Challenge
    .findAll({
      attributes: {
        include: [[Sequelize.fn('count', Sequelize.col('AcceptedChallenges.userId')), 'attempts'],
        [Sequelize.fn('count', Sequelize.col('a.met')), 'met']]
      },
      include: [{
        model: AcceptedChallenge, attributes: [],
        required: false,
      }, {
        model: AcceptedChallenge, attributes: [],
        as: 'a',
        where: { userId: id, met: true },
        required: false,
      }],
      group: ['Challenge.id']
    })
    .catch((e) => {
      console.log("error:", e);
      throw new HTTP404Error('Challenges not found');
    });
  return challenges;
};

It is not recognizing my associations.它不承认我的协会。 Please advise.请指教。 The version here results in: SequelizeEagerLoadingError: AcceptedChallenge is associated to Challenge using an alias. You've included an alias (a), but it does not match the alias(es) defined in your association (AcceptedChallenges).此处的版本导致: SequelizeEagerLoadingError: AcceptedChallenge is associated to Challenge using an alias. You've included an alias (a), but it does not match the alias(es) defined in your association (AcceptedChallenges). SequelizeEagerLoadingError: AcceptedChallenge is associated to Challenge using an alias. You've included an alias (a), but it does not match the alias(es) defined in your association (AcceptedChallenges).

When including the AcceptedChallenge model just once, it calculates attempts just fine.当只包含AcceptedChallenge模型一次时,它计算尝试次数就好了。 I am perplexed as to how I could do the include/JOIN multiple times to get the result, which I need from a single SQL request.我对如何多次执行 include/JOIN 以获得结果感到困惑,这是我从单个 SQL 请求中需要的。

This works for me when the association is repeated, once for each alias needed in your query (example below, but obviously your association may be different).当关联重复时,这对我有用,对于查询中需要的每个别名一次(下面的示例,但显然您的关联可能不同)。

ChallengeController.hasMany(AcceptedChallenge,  {as: 'a', foreignKey: 'challengeId'});
ChallengeController.hasMany(AcceptedChallenge,  {as: 'b', foreignKey: 'challengeId'});
ChallengeController.hasMany(AcceptedChallenge,  {as: 'c', foreignKey: 'challengeId'});

Are you doing something similar?你在做类似的事情吗?

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

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