问题
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
});
I get following error:
Unhandled rejection Error: Only HasMany associations support include.separate
If I try to switch to "HasMany" associations I get following error
Error: N:M associations are not supported with hasMany. Use belongsToMany instead
And from other side documentation says that limit option "only supported with include.separate=true". How to solve this problem?
回答1:
I know this question is old but for those of you still experiencing this issue, there's a simple workaround.
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.
回答2:
Having the same exact problem here. From what I gathered, to use limit/offset you need the include.separate, which isn't supported for belongsToMany associations yet, so what you're trying to do isn't supported at the time of this post.
There's already someone working on it, you can track it here.
来源:https://stackoverflow.com/questions/34118914/how-to-limit-joined-rows-many-to-many-association-in-sequelize-orm