How to limit joined rows (many-to-many association) in Sequelize ORM?(如何限制 Sequelize ORM 中的连接行(多对多关联)?)
问题描述
Sequelize 定义了两种模型:Post 和 Tag 与多对多关联.
There are two models defined by Sequelize: Post and Tag with many-to-many association.
Post.belongsToMany(db.Tag, {through: 'post_tag', foreignKey: 'post_id', timestamps: false});
Tag.belongsToMany(db.Post, {through: 'post_tag', foreignKey: 'tag_id',timestamps: false});
在标签"页面上,我想获取标签数据、相关帖子并通过分页显示它们.所以我应该限制帖子.但是如果我尝试将它们限制在包含"中
On a "tag" page I want to get tag data, associated posts and show them with pagination. So I should limit posts. But If I try limit them inside "include"
Tag.findOne({
where: {url: req.params.url},
include: [{
model : Post,
limit: 10
}]
}).then(function(tag) {
//handling results
});
我收到以下错误:
Unhandled rejection Error: Only HasMany associations support include.separate
如果我尝试切换到HasMany"关联,我会收到以下错误
If I try to switch to "HasMany" associations I get following error
Error: N:M associations are not supported with hasMany. Use belongsToMany instead
从其他方面的文档中说,限制选项仅支持 include.separate=true".如何解决这个问题?
And from other side documentation says that limit option "only supported with include.separate=true". How to solve this problem?
推荐答案
我知道这个问题很老了,但是对于那些仍然遇到这个问题的人来说,有一个简单的解决方法.
I know this question is old but for those of you still experiencing this issue, there's a simple workaround.
由于 Sequelize 向实例添加了 自定义方法关联模型,你可以将你的代码重组为这样的:
Since Sequelize adds custom methods to instances of associated models, you could restructure your code to something like this:
const tag = await Tag.findOne({ where: { url: req.params.url } });
const tagPosts = await tag.getPosts({ limit: 10 });
这将与您的代码完全相同,但可以进行限制和偏移.
This would work the exact same way as your code but with limiting and offsetting possible.
这篇关于如何限制 Sequelize ORM 中的连接行(多对多关联)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何限制 Sequelize ORM 中的连接行(多对多关联)?


基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01