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

时间:2016-10-06 20:32:07

标签: javascript bookshelf.js knex.js

我有以下表格:

  • books
  • book_reviews
  • users

以下是与所述表格对应的模型:

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表,而这些表目前并没有。我该如何将它们链接在一起?

1 个答案:

答案 0 :(得分:0)

如果你这样做:

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);
  });