我有以下型号:
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)
};
我的数据库表是这样的:
user:id,name,username,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": "{}"
}
我的代码出了什么问题?
答案 0 :(得分:1)
我找到了答案:
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});
});