Accessing nested relations in Bookshelf.js

谁说我不能喝 提交于 2019-12-10 09:51:59

问题


I guess you could say I'm building a reddit style app. So I have a topic, and that topic has comments, and those comments have parent comments, etc. Here is my Comment model:

var Comment = bookshelf.Model.extend({

  tableName: 'comments',

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

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

});

And so in my .get('/topic') page, i load my comments like this:

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

So what this does for me is fetch all top level comments, and nests all the children comments up to 4 levels deep. What I need to do with each comment is check a table named 'votes' where 'comment_id' is that comment's id and where 'account_id' is the current req.user's account id and attach from the column 'vote_type' (which would be 'up' or 'down') for each comment. Any insight into this problem would be great.

P.S. For bonus points, any recommendations for how I could replace withRelated: ['children.children.children.children'] and just load all child comments until they have all been loaded? Thanks for your time :)


回答1:


So the solution was to drop back to knex, grab all my comments for that topic with all related data, then build a tree. Here's the query I wound up using. Big thanks to rhys-vdw in the #bookshelf channel on irc.

                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)


来源:https://stackoverflow.com/questions/32540746/accessing-nested-relations-in-bookshelf-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!