Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit joined rows (many-to-many association) in Sequelize ORM?

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?

like image 876
femalemoustache Avatar asked Dec 06 '15 15:12

femalemoustache


2 Answers

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.

like image 76
Gasoline and Sauce Avatar answered Sep 28 '22 07:09

Gasoline and Sauce


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.

like image 25
Diogo Dias Avatar answered Sep 28 '22 07:09

Diogo Dias