Sequelize定义了两种模型:具有多对多关联的Post和Tag。

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

在“标签”页面上,我想获取标签数据,关联的帖子并通过分页显示。所以我应该限制职位。但是如果我尝试将它们限制在“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”关联,则会出现以下错误
Error: N:M associations are not supported with hasMany. Use belongsToMany instead

并且从另一面的文档说,限制选项“仅在include.separate = true中受支持”。如何解决这个问题呢?

最佳答案

我知道这个问题很旧,但是对于仍然遇到此问题的人,有一个简单的解决方法。

由于Sequelize将custom methods添加到关联模型的实例中,因此您可以将代码重组为以下形式:

const tag = await Tag.findOne({ where: { url: req.params.url } });
const tagPosts = await tag.getPosts({ limit: 10 });

这将与您的代码完全一样地工作,但可能会产生限制和抵消。

10-05 20:28
查看更多