如何一次从多个表中获取书架模型

How to get bookshelf model from multiple tables at once

我正在开发一个看起来像拍卖的 node.js 网络服务。我对模型使用 bookshelf.js,对数据库使用 MySQL。 请考虑以下数据库结构:

users:
id     |     login     |     password     |
users_roles:
id     |     user_id     |     role_id          |
roles:
id      |     name     |
auctions:
id      |     user_id     |     rating_id     |
rating:
id      |     speed     |     quality          |     communication     |

目前我实现的用户模型如下:

 var Bookshelf = require('./bookshelf_model'),
    Role = require("./role");

var User = Bookshelf.Model.extend({
        tableName: 'users',

        role: function () {
            return this.belongsToMany(Role, 'users_roles', 'user_id', 'role_id');
        }
    });

module.exports = User;

我可以通过

获取用户详细信息
User.forge({id: 1}).fetch().then(
      function(userDetails){
          .......
      }
    );

此 returns 用户的详细信息来自用户 table。要获得用户角色,我必须再进行一次数据库调用,例如:

User.forge({id: 1}).role().fetch().then(
      function(userRoleDetails){
          .....
      }
    );

有没有什么方法可以使用 bookshelf.js(或使用其他任何方法)一次获取所有用户信息?如果能立刻得到这样的东西那就太好了:

user={
 id:...,
 login:...,
 password:...,
 role_id:....,
 rating:/*avg rating from all user's auctions*/

}

尝试这样的事情:

return User.forge( { id: 1 } ) .fetch( { require: true, //throws error if not found withRelated: [ 'role' ] } ) .then( function( userModel ) { return userModel.toJSON(); //don't need this step, depends what you want to do next } )

类似的东西。这会将 user_roles 对象加载到用户中,并带有 role 属性。一些文档 here