如何在Node.js中将3个表与Bookshelf连接起来

时间:2015-09-25 08:05:03

标签: node.js bookshelf.js

所以我有表格user,表格book和表格user_book_xref

user_book_xrefuser_id

中有id个fk到user

user_book_xrefbook_id

中有id个fk到book

如何选择来自id = 1的用户的所有图书?

1 个答案:

答案 0 :(得分:4)

您需要使用belongsToMany关系,并且由于您已在约定之外命名了连接表,因此您需要在函数中指定它。然后,您需要获取用户并在获取选项中传递关系。

// set up models with relationships
var Book = bookshelf.Model.extend({
    tableName: 'book'
});
var User = bookshelf.Model.extend({
    tableName: 'user',
    books: function() {
        return this.belongsToMany(Book, 'user_book_xref');
    }
});

// query the user using withRelated
return User.forge({id: 1})
.fetch({withRelated:['books']})
.then(function(result) {
    // return only the book
    return result.toJSON().books;
});