【发布时间】:2016-02-28 07:21:02
【问题描述】:
我希望baffle.where({id: 1}).fetch() 始终将typeName 属性作为baffle 模型的一部分,而不是每次都明确地从baffleType 获取它。
以下内容对我有用,但如果baffle 模型是直接获取的,而不是通过关系,似乎withRelated 将加载关系:
let baffle = bookshelf.Model.extend({
constructor: function() {
bookshelf.Model.apply(this, arguments);
this.on('fetching', function(model, attrs, options) {
options.withRelated = options.withRelated || [];
options.withRelated.push('type');
});
},
virtuals: {
typeName: {
get: function () {
return this.related('type').attributes.typeName;
}
}
},
type: function () {
return this.belongsTo(baffleType, 'type_id');
}
});
let baffleType = bookshelf.Model.extend({});
这样做的正确方法是什么?
【问题讨论】:
标签: node.js bookshelf.js knex.js