简体   繁体   English

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

[英]How to relate 3 tables together in Bookshelf.js

I've got the following tables: 我有以下表格:

  • books
  • book_reviews
  • users

Here are the models that correspond to said 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');
  }
});

I'm looking up a Book and trying to fetch all reviews that it has, which it currently is doing with the following statement: 我正在查找一本书,并尝试获取其拥有的所有评论,该书目前正在通过以下语句进行处理:

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

}; };

And the output from book.toJSON() from above looks like: 上面的book.toJSON()的输出看起来像:

Output from book.toJSON() from above: 从上面的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) } ] }

But my intent is that each of the reviews would have a reference to the users table, which they currently don't. 但我的意图是,每个reviews都将引用users表,而他们目前没有。 How can I link those together? 如何将它们链接在一起?

What if you do: 如果您这样做:

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

?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM