问题描述
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 中限制连接行(多对多关联)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!