[英]How to limit joined rows (many-to-many association) in Sequelize ORM?
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});
在“標簽”頁面上,我想獲取標簽數據、相關帖子並通過分頁顯示它們。 所以我應該限制帖子。 但是如果我嘗試將它們限制在“包含”中
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”。 如何解決這個問題呢?
這里有同樣的問題。 從我收集的內容到使用限制/偏移量,你需要include.separate,這對於belongsToMany關聯還不支持,所以在這篇文章發表時你不支持你想要做的事情。
已經有人在做,你可以在這里跟蹤它。
我知道這個問題很老但是對於那些仍然遇到這個問題的人來說,有一個簡單的解決方法。
由於Sequelize將自定義方法添加到關聯模型的實例,因此您可以將代碼重構為以下內容:
const tag = await Tag.findOne({ where: { url: req.params.url } });
const tagPosts = await tag.getPosts({ limit: 10 });
這將與您的代碼完全相同,但可以進行限制和偏移。
我知道這是一個非常古老的問題,尚未得到解答。
正如前面的答案所提到的, belongsToMany關聯不支持限制或偏移。
在處理多對多關系時,將限制和偏移移到包含數組之外,盡管您已經以 findOne() 的形式進行查詢,但在外部級別傳遞限制或偏移量將僅在包含數組中的內部關系上被激活在多對多關系中
它將自動處理內部結果限制和偏移量
Tag.findOne({
where: {url: req.params.url},
include: [{
model : Post,
limit: 10 ❌ ( only exists in hasMany() )
}]
limit:10, ✅ ( This will solve your issue )
}).then(function(tag) {
//handling results
});
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.