node.js - 在 Bookshelf.js 中访问嵌套关系

标签 node.js 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”的表,其中“comment_id”是该评论的 ID,“account_id”是当前 req.user 的帐户 ID,并从“vote_type”列(将是“向上'或'向下')为每个评论。对这个问题的任何见解都会很棒。

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

最佳答案

所以解决方案是回到 knex,获取我对该主题的所有评论以及所有相关数据,然后构建一棵树。这是我最后使用的查询。非常感谢 irc 上#bookshelf channel 中的 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)

关于node.js - 在 Bookshelf.js 中访问嵌套关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540746/

相关文章:

mysql - 用于 NodeJS MySQL 的 ORM 工具

node.js - BookshelfJS 在 FetchAll 中限制 withRelated 不起作用

node.js - Node http.大文件传输失败并显示 'ERR_STREAM_PREMATURE_CLOSE'

node.js - 以 CSV 格式获取 Google Drive 电子表格的内容

node.js - 从 S3 下载文件夹时中断功能

MySql - 字段 'park_id' 没有默认值

javascript - 函数未定义,Bookshelf.js 模型函数未被识别为函数

node.js - 克尼克斯 :Error Pool2 - Error: Error allocating resources: connect ECONNREFUSED

javascript - 弃用警告 : Collection#find: pass a function instead

javascript - 从nodejs中的http请求获取值