始终从Bookshelf.js中的相关模型中获取
我希望baffle.where({id: 1}).fetch()
总是将typeName
属性作为baffle
模型的一部分,而不是baffleType
明确地从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({});
什么是正确的方法来做到这一点?
这个问题已经很老了,但是我仍然在回答。
我通过添加一个新的函数fetchFull
来解决这个问题。
let MyBaseModel = bookshelf.Model.extend({ fetchFull: function() { let args; if (this.constructor.withRelated) { args = {withRelated: this.constructor.withRelated}; } return this.fetch(args); }, }; let MyModel = MyBaseModel.extend({ tableName: 'whatever', }, { withRelated: [ 'relation1', 'relation1.related2' ] } );
然后,无论何时查询,您都可以调用Model.fetchFull()
来加载所有内容,或者在您不想执行性能冲击的情况下,仍然可以使用Model.fetch()
。
回购问题与Fetched
事件有关,但是Fetching
事件工作正常(v0.9.2)
。
举个例子,如果你有第三个模型
var Test = Bookshelf.model.extend({ tableName : 'test', baffleField : function(){ return this.belongsTo(baffle) } })
然后做Test.forge().fetch({ withRelated : ['baffleField']})
,挡板上的fetching
事件将会触发。 但是,除非你明确地告诉它这样做,否则ORM
将不包括type
(sub相关模型)
Test.forge().fetch({ withRelated : ['baffleField.type']})
但是我会try to avoid
这种情况,如果它正在N Query
N records
。
更新1
我正在谈论你正在做的事情
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
更改而失败。