Node.js 如何使用关系丰富的书架查询数据?

Node.js 如何使用关系丰富的书架查询数据?,node.js,bookshelf.js,knex.js,Node.js,Bookshelf.js,Knex.js,因此,我有以下几点: var Device = services.bookshelf.Model.extend({ tableName: 'device', calendar: function() { return this.belongsToMany(Calendar, 'calendar_device', 'deviceId', 'calendarId'); } }); var Calendar = module.exports = service

因此,我有以下几点:

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);
    }
});
关系还在继续。。。 例如,我应该如何进行查询以获取设备的频道?我不知道我是否遗漏了什么,但我没有找到太多关于这个的信息

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: [
            ...
        ]
    ]
}