在Bookshelf JS中使用相关的集合
在使用Bookshelf Collections时遇到问题,而在API级别的文档中找不到答案,这很难说明如何将各个部分组合在一起。
使用Bookshelf的以下设置,包括模型registry插件:
const knexConfig = require('../knexfile')[process.env.NODE_ENV || 'development']; const knex = require('knex')(knexConfig); const bookshelf = require('bookshelf')(knex); bookshelf.plugin('registry');
假设存在以下模型:
const Foo = bookshelf.model('Foo', { tableName: 'foos', bars: function() { return this.hasMany('Bar'); } }); const Bar = bookshelf.model('Bar', { tableName: 'bars', foo: function() { return this.belongsTo('Foo'); } });
我们有一些批量操作,我们希望在整个Bar
对象集上执行。 我们不想迭代每个Bar
,而是希望将其减less为单个查询。 所以我们创build一个Bars
的集合:
const Bars = bookshelf.Collection.extend({ model: 'Bar', bulkOperation: function() { // contrived example return this.query.save({field: 'value'}); } });
当实际运行给定Foo
's Bars
的批量操作时,我们发现bars.bulkOperation()
不是Bars
Collection
,而只是一个CollectionBase
。
Foo .where({id: 1}) .fetch({withRelated: 'bars'}) .then(foo => foo.related('bars')) .then(bars => bars.bulkOperation()); // bars.bulkOperation is not a function
显然, CollectionBase
没有在其上定义bulkOperation
。
我们如何从related('bars')
得到一个Bars
Collection
,以便我们可以用尽批量操作?