在Bookshelf.js中访问嵌套关系

3

我想你可以说我正在构建一个 Reddit 风格的应用程序。所以我有一个主题,这个主题下面有评论,这些评论又有父评论等等。这是我的评论模型:

var Comment = bookshelf.Model.extend({

  tableName: 'comments',

  topic: function() {
    return this.belongsTo(Topic, 'topic_id');
  },

  children: function() {
    return this.hasMany(Comment, 'parent_id')
  }

});

在我的 .get('/topic') 页面中,我是这样加载评论的:

new Comment()
  .query({where: {topic_id: topic_id}})
  .query({where: {parent_id: null}})
  .fetchAll({
    withRelated: ['children.children.children.children']
  })

所以,这对我做的事情是获取所有顶级评论,并将所有子评论嵌套到4级深度。我需要对每个评论执行的操作是检查名为'votes'的表,其中'comment_id'是该评论的id,'account_id'是当前req.user的帐户id,并为每个评论附加来自列'vote_type'的内容(可能是'up'或'down')。对此问题的任何见解都将是很好的。
附加问题:有没有建议如何替换withRelated:['children.children.children.children'],并加载所有子评论,直到它们全部加载完毕?谢谢您的时间 :)

从您的描述中很难理解您想要的关系是什么样子的,但就嵌套评论而言,您可以编写一个递归函数,获取所有子评论,直到没有子评论为止,并将所有内容合并到单个数据结构中。 - vbranden
1个回答

3

所以解决方案是回到knex,获取所有相关数据的主题评论,然后构建一棵树。以下是我最终使用的查询语句。非常感谢在IRC的#bookshelf频道中的rhys-vdw。

                knex('comments').leftOuterJoin('votes', function() {
                    this.on('comments.id', 'votes.comment_id')
                        .andOn(knex.raw('votes.account_uuid = ?', req.user.uuid));
                })
                .leftOuterJoin('vote_count', function() {
                    this.on('comments.id', 'vote_count.comment_id');
                })
                .select('comments.*', 'votes.vote_type', 'vote_count.upvotes', 'vote_count.downvotes')
                .where('comments.topic_id', '=', topic_id)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接