Search code examples
javascriptbookshelf.jsknex.js

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:

Output from book.toJSON() from above:

{ 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. How can I link those together?


Solution

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

    ?