访问 Bookshelf.js 中的嵌套关​​系

Accessing nested relations in Bookshelf.js

我想你可以说我正在构建一个 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' 的 table,其中 'comment_id' 是评论的 ID,'account_id' 是当前 req.user 的帐户ID 并从 'vote_type' 列(即 'up' 或 'down')附加到每个评论。对这个问题的任何见解都会很棒。

P.S。对于奖励积分,关于如何替换 withRelated: ['children.children.children.children'] 并加载所有子评论直到它们全部加载的任何建议?感谢您的宝贵时间:)

所以解决方案是回到 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)