有谁知道为什么我无法访问给定author
的相关 book
?
console.log(book.related('author').toJSON());
会打印空对象。
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 } }
答案 0 :(得分:0)
我现在无法测试,但模型定义中对require()的调用对我来说很奇怪......我会写的
author: function() {
return this.belongsTo(Author);
}
和
books: function(){
return this.hasMany(Book, 'author_id');
}
PS。由于我无法立即测试,我想将此作为评论但我没有足够的声誉......