如何通过多个连接表

时间:2016-04-12 19:34:14

标签: node.js postgresql bookshelf.js knex.js

我有三个模型:EventGalleryImageImage是基本模型,代表单个媒体。 Gallery是用户提交的Images的集合。用户仅与Images级别的Gallery进行互动,因为他们以单数Images的形式创建,修改和删除Galleries组。 EventGalleries的集合,可将内容与特定的真实世界事件相关联。

所以,我的关系如下:Event -> Event_Galleries -> Gallery -> Gallery_Images -> Image

我的问题是,通过Bookshelf,有没有办法使用现有的连接表来指定从EventImage的关系?它的功能如下:

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

1 个答案:

答案 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);
})