gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:24:53 24 4
gpt4 key购买 nike

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

关于postgresql - 如何将复杂的 GROUP BY 转换为 Sequelize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com