2014-10-10 97 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标识的类别下的帖子的正确值。