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 :)
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.