Search code examples
node.jspostgresqlbookshelf.jsknex.js

How to join objects through via multiple join tables


I have three models: Event, Gallery and Image. An Image is the base model, and represents a single piece of media. A Gallery is a collection of Images submitted by a user. Users only interact with Images on the Gallery level, in that they create, modify and delete groups of Images at the time in the form of singular Galleries. An Event is a collection of Galleries which associate the content with specific real-world events.

So, my relations are as follows: Event -> Event_Galleries -> Gallery -> Gallery_Images -> Image

My question is, through Bookshelf, is there a way to specify a relationship from the Event to the Image using both the existing join tables? It would function as follows:

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


Solution

  • Yes, you can specify relationships in a Bookshelf.js model, following this way :

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