如何在 Bookshelf.js 中将 3 个表关联在一起

How to relate 3 tables together in Bookshelf.js

我有以下 tables:

以下是与所述 tables 相对应的模型:

const BookReview = require('./BookReview').model;
const User = require('./User').model;

module.exports.model = bookshelf.Model.extend({
  tableName: 'books',

  user: function() {
    return this.hasOne(User, 'user_id');
  },

  reviews: function() {
    return this.hasMany(BookReview);
  }
});

module.exports.model = bookshelf.Model.extend({
  tableName: 'book_reviews',

  user: function() {
    this.hasMany(User, 'user_id');
  }
});

module.exports.model = bookshelf.Model.extend({
  tableName: 'users',

  reviews: function() {
    return this.belongsToMany(BookReview, 'user_id');
  }
});

我正在查找一本书并尝试获取它拥有的所有评论,目前它正在使用以下语句执行此操作:

return Book.forge({
    id: req.params.id,
    type: req.params.type
  }).fetch({withRelated: ['reviews'], require: true}).then(function(book) {
    console.log(book.toJSON());
    return book;
  }).catch(function(err) {
    throw new Error(err.message);
  });

};

上面 book.toJSON() 的输出如下所示:

上面 book.toJSON() 的输出:

{ id: 1,
  type: 'novel',
  slug: 'catcher-in-the-rye',
  user_id: 1,
  name: 'Catcher in the Rye',
  created_at: Tue Oct 04 2016 22:35:42 GMT-0700 (PDT),
  updated_at: Tue Oct 04 2016 22:35:42 GMT-0700 (PDT),
  reviews: 
   [ { id: 14,
       user_id: 2,
       book_id: 1,
       rating: 3,
       review: 'Test',
       created_at: Wed Oct 05 2016 20:47:34 GMT-0700 (PDT),
       updated_at: Wed Oct 05 2016 20:47:34 GMT-0700 (PDT) } ] }

但我的意图是每个 reviews 都将引用 users table,而他们目前没有。我怎样才能link那些在一起?

如果你这样做会怎样:

return Book.forge({
    id: req.params.id,
    type: req.params.type
  }).fetch({withRelated: ['reviews', 'reviews.user'], require: true}).then(function(book) {
    console.log(book.toJSON());
    return book;
  }).catch(function(err) {
    throw new Error(err.message);
  });

?