如何查询与书架有很多关系的数据?

所以,我有以下几点:

var Device = services.bookshelf.Model.extend({ tableName: 'device', calendar: function() { return this.belongsToMany(Calendar, 'calendar_device', 'deviceId', 'calendarId'); } }); var Calendar = module.exports = services.bookshelf.Model.extend({ tableName: 'calendar', device: function() { return this.belongsToMany(Device, 'calendar_device', 'calendarId', 'deviceId'); }, schedule: function() { return this.hasMany(Schedule); } }); var Schedule = module.exports = services.bookshelf.Model.extend({ tableName: 'schedule', calendar: function() { return this.belongsTo(Calendar); }, channel: function() { return this.hasMany(Channel); } }); var Channel = module.exports = services.bookshelf.Model.extend({ tableName: 'channel', schedule: function() { return this.belongsTo(Schedule); }, screenItem: function() { return this.hasMany(ScreenItem); } }); 

而且这种关系还在继续……我应该如何查询以获取设备的渠道? 我不知道我是否错过了一些东西,但是我没有在这方面find太多的信息。

 Device.where('id', id).fetch({withRelated: ['calendar.schedule.channel']}).then(function(devices) { ... }) 

我所做的是获取设备'id'= id指定我想要返回的模型的关系(这是声明,因为它可以在我的问题中的模型声明中看到)。 所以说:

  • {withRelated:['calendar']}返回一个设备及其日历
  • {withRelated:['calendar.schedule']}返回一个设备及其日历的日历
  • {withRelated:['calendar.schedule.channel']}返回一个设备,其日历及其通道的时间表

等等,如果有更多的相关模型,你想得到的。

答案是这样的:

 { id: 1, ..., calendars: [ id: 1, ..., schedules: [ ... ] ] }