如何限制 Sequelize ORM 中的连接行(多对多关联)?

2022-01-19 00:00:00 node.js javascript sequelize.js

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.

相关文章