如何获取模型的所有行及其关系?

How do I fetch all rows of a model with its relations?

我有以下型号:

role.js

let bookshelf = require('../config/database');

var Role,
    Roles;

Role = bookshelf.Model.extend({
    tableName: 'roles',
    users: function() {
        return this.hasMany('User');
    }
});

Roles = bookshelf.Collection.extend({
    model: Role
});

module.exports = {
    Role: bookshelf.model('Role', Role),
    Roles: bookshelf.collection('Roles', Roles)
};

user.js

let bookshelf = require('../config/database');

var User,
    Users;

User = bookshelf.Model.extend({
    tableName: 'users',
    role: function() {
        return this.hasOne('Role');
    }
});

Users = bookshelf.Collection.extend({
    model: User
});

module.exports = {
    User: bookshelf.model('User', User),
    Users: bookshelf.collection('Users', Users)
};

我的数据库表是这样的:

用户:id,姓名,用户名,role_id 角色:id,描述

我需要获取所有用户的角色(ID 和描述),然后我尝试这样做:

User.where({})
            .fetch({withRelated: ['role']})
            .then(function(result) {
                res.json({data: result.toJSON()});
            })
            .catch(err => {
                res.json({error: JSON.stringify(err)});
            });

但我得到的只是:

{
    "error": "{}"
}

我的代码有什么问题?

我找到了答案:

User.forge()
            .fetchAll({withRelated: ['role']})
            .then(function(result) {
                if (result === null)
                    res.json({data: []});
                else
                    res.json({data: result.toJSON()});
            })
            .catch(err => {
                res.json({error: err.message});
            });