我正在使用sequelize.js构建一个项目,其中包括一个tags表和一个stories表。他们有一个多对多的关系,我在sequelize中创建了一个贯穿storytag表。到目前为止,这一切都非常有效,但是我想得到一个大多数popluar标记的列表,比如在storytag表中与它们关联的故事数,并按照使用这个标记的故事数对它们进行排序。
这就是我要做的mysql语法。这在mysql workbench中非常有效:
SELECT tagName, COUNT(StoryTag.TagId)
FROM Tags
LEFT JOIN StoryTag on Tags.id = StoryTag.TagId
GROUP BY Tags.tagName ORDER BY COUNT(StoryTag.TagId) DESC;
这就是sequelize.js的工作原理。这是一个原始的查询,并不理想,但由于它不处理任何敏感信息,所以这不是一个大问题,只是非常不雅。
//DIRECT QUERY METHOD (TEST)
app.get("/api/directags", function (req, res) {
db.sequelize.query("select tags.id, tags.TagName, COUNT(stories.id) as num_stories
from tags left join storytag on storytag.TagId = tags.id
left join stories on storytag.StoryId = stories.id
group by tags.id order by num_stories desc;", {
type: db.Sequelize.QueryTypes.SELECT
}).then(function(result) {
res.send(result);
});
});
这个输出
[
{
"id": 3,
"TagName": "fiction",
"num_stories": 3
},
{
"id": 5,
"TagName": "Nursery Rhyme",
"num_stories": 2
},
...
{
"id": 4,
"TagName": "nonfiction",
"num_stories": 0
}
]
应该的。
不太管用的是:
//Sequelize count tags
//Known issues: will not order by the count
//Includes a random 'storytag' many-to-many table row for some reason
app.get("/api/sequelizetags", function (req, res) {
db.Tag.findAll({
attributes: ["id","TagName"],
include: [{
model: db.Story,
attributes: [[db.sequelize.fn("COUNT", "stories.id"), "Count_Of_Stories"]],
duplicating: false
}],
group: ["id"]
}).then(function (dbExamples) {
res.send(dbExamples);
});
});
输出:
[
{
"id": 1,
"TagName": "horror",
"Stories": [
{
"Count_Of_Stories": 1,
"StoryTag": {
"createdAt": "2018-11-29T21:09:46.000Z",
"updatedAt": "2018-11-29T21:09:46.000Z",
"StoryId": 1,
"TagId": 1
}
}
]
},
{
"id": 2,
"TagName": "comedy",
"Stories": []
},
{
"id": 3,
"TagName": "fiction",
"Stories": [
{
"Count_Of_Stories": 3,
"StoryTag": {
"createdAt": "2018-11-29T21:10:04.000Z",
"updatedAt": "2018-11-29T21:10:04.000Z",
"StoryId": 1,
"TagId": 3
}
}
]
},
{
"id": 4,
"TagName": "nonfiction",
"Stories": []
},
...
{
"id": 8,
"TagName": "Drama",
"Stories": [
{
"Count_Of_Stories": 1,
"StoryTag": {
"createdAt": "2018-11-30T01:13:56.000Z",
"updatedAt": "2018-11-30T01:13:56.000Z",
"StoryId": 3,
"TagId": 8
}
}
]
},
{
"id": 9,
"TagName": "Tragedy",
"Stories": []
}
]
这是不正常的,故事的计数被埋葬了。这似乎是一种常见的、频繁的来自数据库的请求,但我不知道如何使用sequelize.js正确地执行此操作。
使我失败的资源:
续集在多对多的地方加入
继续多对多查询问题
sequelize中如何查询多对多关系数据
从多对多关系中选择
sequelize的官方文件:http://docs.sequelizejs.com/manual/tutorial/
sequelize的一些不太正式、可读性更高的文档:https://sequelize.readthedocs.io/en/v3/docs/querying/
3条答案
按热度按时间guykilcj1#
使用
through: {attributes: []}
在选项中ca1c2owp2#
这是最后的结果,以防其他人有这个问题。我们还为include故事添加了一个where,但这是可选的。此资源比官方的sequelize文档更容易理解:https://sequelize-guides.netlify.com/querying/
我还了解到,在使用sequelize时,熟悉承诺确实很有帮助。
i7uaboj43#
如果你的意思是一样的,请用同样的名字(
num_stories
-Count_Of_Stories
等)。供订购使用
order
选项。包括
count
在顶级属性中,获取示例的顶级属性。我找不到
include[].duplicating
文件中的选项。您的案例: