如何在Node.js中使用Bookshelf连接3个表

所以我有表user ,例如表格和user_book_xref表。

user_book_xrefuseruser_id fk到id

user_book_xrefbookbook_id fk到id

如何从id = 1的用户中select所有书籍?

您需要使用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; });