簡體   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