如何将复杂的 GROUP BY 转换为 Sequelize?

How do I convert a complex GROUP BY to Sequelize?

我的SQL查询是

SELECT t."id", t."topicText", COUNT(t."id") AS topicCount 
FROM "WorkbookQuestions" wq, "Workbooks" w, "Questions" q, "Topics" t 
WHERE  w."StudentId" = 3 
  AND wq."QuestionId" = q."id" 
  AND wq."WorkbookId" = w."id" 
  AND q."TopicId" = t."id"
GROUP BY "t"."id"
ORDER BY "topiccount" DESC

如何在 Sequelize 代码中编写此代码,以避免直接编写 SQL?还是不可能?

这是我到目前为止(未成功)尝试过的方法:

db.WorkbookQuestion.findAll({
  attributes: ['Topics.id', [db.sequelize.fn('COUNT', db.sequelize.col('Topics.id'))], 'TopicCount'],
  include: [
    {
      model: db.Workbook,
      where: {
        StudentId: newWorkbook.StudentId,
        SubjectId: newWorkbook.SubjectId
      }
    }, {
      model: db.Question,
      include: [
        {
          model: db.Topic
        }
      ]
    }
  ],
  group: ['Topics.id']
});

光是看,我就会这样写代码

db.Workbook.findAll({
  attributes: ['wbquestion.question.topic.id', [db.sequelize.fn('COUNT', db.sequelize.col('wbquestion.question.topic.id'))], 'topiccount'],
  include: [
    {
      model: db.WorkbookQuestion,
            as: wbquestion,
      where: {
                id: wbquestion.workbookId      
            },
            include: [
                model: db.Question,
                as: question,
                where: {
                    id: wbquestion.questionId
                },
                include: [
                    model: db.Topic,
                    as: topic,
                    where: {
                        id: question.topicId
                    }
                ]
            ]
    }
  ],
    where: {
        studentId : 3
    }
  group: ['topic.id']
});

也许您可以通过分别定义模型和关系并在之后使用预先加载来获得更具可读性的代码。

编辑: 生成迁移和模型

node_modules/.bin/sequelize model:create --name Student --attributes firstName:string,lastName:string
node_modules/.bin/sequelize model:create --name Topic --attributes topicText:string
node_modules/.bin/sequelize model:create --name Question --attributes TopicId:integer
node_modules/.bin/sequelize model:create --name Workbook --attributes studentId:integer
node_modules/.bin/sequelize model:create --name WorkbookQuestion --attributes QuestionId:integer,WorkbookId:integer

用于在控制台日志中测试查询的简单程序。

var Sequelize = require("sequelize");

var models = require('./models/index');

models.WorkbookQuestion.belongsTo(models.Question, {foreignKey: 'QuestionId'});
models.WorkbookQuestion.belongsTo(models.Workbook, {foreignKey: 'WorkbookId'});

models.Question.hasOne(models.WorkbookQuestion);

models.Workbook.hasOne(models.WorkbookQuestion);
models.Workbook.belongsToMany(models.Question, {through: models.WorkbookQuestion});
models.Workbook.belongsToMany(models.Topic, {through: models.Question});


var res = models.Workbook.findAll({
    attributes: ['topicId', Sequelize.fn('count', Sequelize.col('topiccount'))],
  include: [models.WorkbookQuestion, models.Question, models.Topic],
    where: {
        studentId: 3
    },
    group: ['topic.id']  
}).then(function(data) {
    console.log(data);
}).catch(function(err) {
    console.trace(err);
});

结果是:

SequelizeDatabaseError: 列 Topics.Question.WorkbookId 不存在

也许您可以修复模型之间的关系,或者您应该创建不使用 findAll 功能的查询。