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

时间:2016-02-26 01:53:01

标签: postgresql sequelize.js

我的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']
});

1 个答案:

答案 0 :(得分:1)

只要看一下,我就会编写像这样的代码

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功能的查询。