我有三个模型:Event
,Gallery
和Image
。 Image
是基本模型,代表单个媒体。 Gallery
是用户提交的Images
的集合。用户仅与Images
级别的Gallery
进行互动,因为他们以单数Images
的形式创建,修改和删除Galleries
组。 Event
是Galleries
的集合,可将内容与特定的真实世界事件相关联。
所以,我的关系如下:Event -> Event_Galleries -> Gallery -> Gallery_Images -> Image
我的问题是,通过Bookshelf,有没有办法使用现有的连接表来指定从Event
到Image
的关系?它的功能如下:
Event
-> Event_Galleries where Event_Galleries.event_id = Event.id
-> Gallery_Image where Event_Galleries.gallery_id = Gallery_Image.gallery_id
-> Image where Image.id = Gallery_Image.image_id
答案 0 :(得分:1)
是的,您可以按照以下方式在Bookshelf.js模型中指定关系:
const Company = db.bookshelf.Model.extend({
tableName: 'companys',
hunters: function employees() {
return this.hasMany(Employee, 'company_id');
}
});
const Employee = db.bookshelf.Model.extend({
tableName: 'employees',
company: function company() {
return this.belongsTo(Company);
},
addresses: function addresses() {
return this.hasMany(EmployeeAddress);
},
});
const EmployeeAddress = db.bookshelf.Model.extend({
tableName: 'employees_addresses',
employee: function employee() {
return this.belongsTo(Employee);
}
});
Company.where({ id: 42 }).fetch([ withRelated: 'employees', 'employees.addresses' ])
.then(result => {
console.log(result);
}, error => {
console.log(error);
})