F
F
femalemoustache2015-12-07 10:53:15
JavaScript
femalemoustache, 2015-12-07 10:53:15

How to fetch with limit for many-to-many models in Sequelize ORM?

There are two models defined with Sequelize: Post and Tag, which are many-to-many related:

Post.belongsToMany(db.Tag, {through: 'post_tag', foreignKey: 'post_id', timestamps: false});
Tag.belongsToMany(db.Post, {through: 'post_tag', foreignKey: 'tag_id',timestamps: false});

For the tag page, I need to get the data about the tag and the posts with the given tag to be displayed with pagination. Those. you must specify the limit and offset attributes for the associated Post model. While the problem with limit. First of all, I tried to just specify it inside the include:
Tag.findOne({
    where: {url: req.params.url},
    include: [{
        model : Post,
        limit: 10
    }]
}).then(function(tag) {
    //handling results
});

I am getting an error:
Unhandled rejection Error: Only HasMany associations support include.separate

I try to change for Tag belongsToMany to hasMany, again I get an error:
Error: N:M associations are not supported with hasMany. Use belongsToMany instead

I look at the documentation about limit inside include: "only supported with include.separate=true".
It turns out a vicious circle: I need to specify a limit for a "many-to-many" relationship, but it is only supported by the relationship type, which cannot be used for "many-to-many".
Are there any options how to solve this problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question