2016-07-21 8 views
0

Ich kämpfe mit Bookshelf.js und ich hoffe, dass jemand mir eine Hand leihen kann.Bookshelf.js Eager Loading Dritte Tabelle

Ich habe Kunden, die Kontakte verschiedener Typen (E-Mail-Adresse, Facebook, Skype, etc.) haben. Also habe ich mich in drei Tabellen aufgeteilt, um die Typen zu normalisieren. Ich kann nicht herausfinden, wie man die Art des Kontaktes richtig abfragt und eifrig lädt. Ich kann die Kontakte bekommen, um sich einfach über

new Customer({id: 1}).fetch({withRelated: ['contacts']}).then((customer) => { 
    console.log(customer.toJSON()); 
    }) 

Aber für das Leben von mir kann ich nicht scheinen, um herauszufinden, wie man diese Kontakte in ihre jeweiligen Typen entsprechen. Rails hat eine Menge davon unter die Decke und darüber bin ich, dass Bedauern darüber ...

Tabellen

customers = knex.schema.createTable('customers', function(t) { 
    t.increments('id').primary(); 
    t.string('emailAddress').notNullable().unique(); 
    t.timestamps(true, true); 
}); 

contacts = knex.schema.createTable('contacts', function(t) { 
    t.increments('id').primary(); 
    t.string('value').notNullable(); 
    t.integer('contact_type_id').references('contact_types.id'); 
    t.string('contactable_type').notNullable(); 
    t.integer('contactable_id').notNullable(); 
}); 

contact_types = knex.schema.createTable('contact_types', function(t) { 
    t.increments('id').primary(); 
    t.string('value').notNullable(); 
}); 

Modelle

const Customer = bookshelf.Model.extend({ 
    tableName: 'customers', 
    contacts: function() { 
    return this.morphMany('Contact', constants.CONTACTABLE); 
    } 
}); 

const Contact = bookshelf.Model.extend({ 
    tableName: 'contacts', 
    contactable: function() { 
    return this.morphTo(constants.CONTACTABLE, 'Customer'); 
    }, 

    type: function() { 
    return this.belongsTo('ContactType'); 
    } 
}); 

const ContactType = bookshelf.Model.extend({ 
    tableName: 'contact_types', 

    contacts: function() { 
    return this.hasMany('Contact'); 
    } 
}); 

Antwort

1

Ich glaube, die Beziehungen in der withRelated Verkettungs Array sollte den Trick machen. Versuchen Sie Folgendes:

new Customer({id: 1}).fetch({withRelated: ['contacts.type']}).then((customer) => { 
    console.log(customer.toJSON()); 
}) 
Verwandte Themen