返回儿童相关表(TaskList> TaskListItem> Vehicle)
问题描述:
考虑到以下模型,我需要返回所有TaskLists
及其TaskListItems
(1-N),最后一个与其各自的Vehicle
(N-1,a车辆可以有一个或多个TaskListItems
,但如果没有车辆,则不会存在TaskListItem
)。返回儿童相关表(TaskList> TaskListItem> Vehicle)
任务列表
TaskListItem
let bookshelf = require('./base');
var TaskListItem,
TaskListItems;
TaskListItem = bookshelf.Model.extend({
tableName: 'tasklist_items',
createdByUser: function() {
return this.belongsTo('User', 'createdBy');
},
vehicle: function() {
return this.belongsTo('Vehicle', 'vehicleId').through('VehicleAnomaly', 'vehicleAnomalyId', 'vehicleId', 'id');
}
});
TaskListItems = bookshelf.Collection.extend({
model: TaskListItem
});
module.exports = {
TaskListItem: bookshelf.model('TaskListItem', TaskListItem),
TaskListItems: bookshelf.collection('TaskListItems', TaskListItems)
};
车辆
let bookshelf = require('./base');
var Vehicle,
Vehicles;
Vehicle = bookshelf.Model.extend({
tableName: 'vehicles'
});
Vehicles = bookshelf.Collection.extend({
model: Vehicle
});
module.exports = {
Vehicle: bookshelf.model('Vehicle', Vehicle),
Vehicles: bookshelf.collection('Vehicles', Vehicles)
};
我已经能够凭借其TaskListItems
返回所有TaskLists
,但我不知道怎么加结果的第三个层次。
new TaskList()
.query(qb => {
qb.join('tasklist_items', 'tasklists.id', '=', 'tasklist_items.tasklistId');
qb.where('tasklist_items.statusId', '=', 1);
})
.fetchAll({
withRelated: [ {
'items': function(qb) {
qb.where('statusId', '=', 1);
}
}]
})
我怎样才能返回TaskLists
,他们TaskListItems
连同TaskListItem
的每个Vehicle
?
答
刚刚找到答案。我万一别人分享过这个需要:
new TaskList()
.query(qb => {
qb.join('tasklist_items', 'tasklists.id', '=', 'tasklist_items.tasklistId');
qb.where('tasklist_items.statusId', '=', 1);
})
.fetchAll({
withRelated: [ {
'items': function(qb) {
qb.where('statusId', '=', 1);
},
'items.vehicle': function(qb) {
qb.orderBy('location', 'ASC');
}
}]
})
的解决方案是将withRelated
阵列中添加新项,指向另一个子模型的子模型(vehicle
)。