繁体   English   中英

使用 Sequelize 多次加入同一个表

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

我正在尝试编写一个大致可以做的查询:

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;

尝试了多个版本,包括以下:

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

它不承认我的协会。 请指教。 此处的版本导致: 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).

当只包含AcceptedChallenge模型一次时,它计算尝试次数就好了。 我对如何多次执行 include/JOIN 以获得结果感到困惑,这是我从单个 SQL 请求中需要的。

当关联重复时,这对我有用,对于查询中需要的每个别名一次(下面的示例,但显然您的关联可能不同)。

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

你在做类似的事情吗?

暂无
暂无

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

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