我希望 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({});
这样做的正确方法是什么?
最佳答案
repo 上的问题与 Fetched
事件有关,但是 Fetching
事件运行良好 (v0.9.2)
.
例如,如果您有第三个模型,例如
var Test = Bookshelf.model.extend({
tableName : 'test',
baffleField : function(){
return this.belongsTo(baffle)
}
})
然后执行 Test.forge().fetch({ withRelated : ['baffleField']})
,baffle 上的 fetching
事件将会触发。但是,ORM
不会包含 type
(子相关模型),除非您通过
Test.forge().fetch({ withRelated : ['baffleField.type']})
但是,如果它为 N 条记录
进行 N 查询
,我会 尽量避免
。
更新 1
我说的是你在 fetching
事件中所做的同样的事情,比如
fetch: function fetch(options) {
var options = options || {}
options.withRelated = options.withRelated || [];
options.withRelated.push('type');
// Fetch uses all set attributes.
return this._doFetch(this.attributes, options);
}
在 model.extend
中。但是,如您所见,这可能会因 version
更改而失败。
关于node.js - 始终从 Bookshelf.js 中的相关模型中获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35679855/