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 中的连接行(多对多关联)?
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01