2014-10-10 92 views
0

我使用bookshelf.js作爲我的ORM for node。我有2個型號通過bookshelf.js分類獲取帖子

Post = bookshelf.Model.extend({ 
    tableName: 'posts', 
    categories: function() { 
     return this.belongsToMany('Category'); 
    } 
}); 

Category = bookshelf.Model.extend({ 
    tableName: 'categories', 
    posts: function() { 
    return this.belongsToMany('Post'); 
    } 
}); 

它們通過categories_posts表相關,因此它有多對多的關係。

現在我希望用戶能夠查看某個類別中的所有帖子。但我不想只是所有的職位,我想分頁。但我無法獲取特定類別下的總帖子,它總是返回系統中存在的帖子總數。

我試過這Category.forge({id: id}).posts().query().count('*').then(function(total) {});,但總數等於posts表中的總職位,而不是id確定的類別下的職位總數。這甚至是可能的,或者我應該制定一個直接查詢categories_posts表的幫助方法?

謝謝。

回答

1

好吧我想我找到了解決方案。

Category.forge({id: id}).fetch({withRelated: [{posts: function(q) { 
    q.count('* AS count'); 
}}]}) 
.then(function(total) { 
    console.log(total.toJSON().posts[0].count); 
}); 

將提供id標識的類別下的帖子的正確值。