我希望
以下对我有效,但似乎
baffle.where({id:1}).fetch()
始终作为baffle模型的一部分获取typeName
属性,而不需要每次显式从baffleType
获取。以下对我有效,但似乎
withRelated
会在直接获取baffle模型时加载关系,而不是通过关系加载: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({});
如何正确地做到这一点?
fetch()
调用中的{ withRelated: ... }
部分,修改options.withRelated
是唯一的选择吗?在应用程序的这个部分,性能并不是关键问题。 - Estus Flaskoverriding
(JS 不好的词)model.extend
中的 fetch 方法。然而,使用fetching
事件更多地是使用 Bookshelf 的方式。重写一个方法是更加干净的方式,但它可能会在版本升级/降级时失败。 - Satyajeetfetch: function (...args) { return bookshelf.Model.prototype.fetch.bind(this)(...args) }
吗? - Estus Flask_doFetch
存在的原因。 - Estus Flask