如何在 Node.js 中使用 Bookshelf 连接 3 个表
How to join 3 tables with Bookshelf in Node.js
所以我有 table user
、table book
和 table user_book_xref
.
user_book_xref
在 user
中有 user_id
fk 到 id
user_book_xref
在 book
中 book_id
fk 到 id
如何 select 来自 id
= 1 的用户的所有书籍?
您需要使用 belongsToMany 关系,并且由于您在约定之外命名了加入 table,因此您需要在函数中指定它。然后您需要获取用户并在获取选项中传递关系。
// 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;
});
所以我有 table user
、table book
和 table user_book_xref
.
user_book_xref
在 user
user_id
fk 到 id
user_book_xref
在 book
book_id
fk 到 id
如何 select 来自 id
= 1 的用户的所有书籍?
您需要使用 belongsToMany 关系,并且由于您在约定之外命名了加入 table,因此您需要在函数中指定它。然后您需要获取用户并在获取选项中传递关系。
// 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;
});