【发布时间】:2015-01-31 15:18:17
【问题描述】:
有谁知道为什么我无法访问给定book 的相关 author?
console.log(book.related('author').toJSON()); 打印一个 empty 对象。
var Book = Bookshelf.Model.extend({
tableName: 'books',
hasTimestamps: true,
author: function() {
return this.belongsTo(require('./author'));
},
});
var Author = Bookshelf.Model.extend({
tableName: 'authors',
hasTimestamps: true,
books: function(){
return this.hasMany(require('./book'), 'author_id');
},
});
在我的GET /books/{id} 路由处理程序中:
var p = new Book({id: req.params.id}).fetch({
withRelated: ['author']
}).then(function(book){
// THIS PRINTS AN EMPTY OBJECT
console.log(book.related('author').toJSON());
return {
book: internals.renderbook(book)
};
});
如果我尝试不打印 .toJSON(),它会显示:
{ attributes: {},
_previousAttributes: {},
changed: {},
relations: {},
cid: 'c12',
relatedData:
{ type: 'belongsTo',
target:
{ [Function]
super_: [Object],
NotFoundError: [Function: ErrorCtor],
collection: [Function],
forge: [Function],
where: [Function],
query: [Function],
fetchAll: [Function],
extend: [Function],
__super__: [Object] },
targetTableName: 'authors',
targetIdAttribute: 'id',
foreignKey: 'user_id',
parentId: 'b3b35d4c-17c3-46bd-90c2-a17fe907b9b8',
parentTableName: 'books',
parentIdAttribute: 'id',
parentFk: undefined } }
【问题讨论】:
标签: hapijs bookshelf.js