Robert John
Robert John

Reputation: 33

Bookshelf.js Eager Loading Third Table

I'm struggling with Bookshelf.js and I'm hoping someone can lend me a hand.

I've customers who have contacts of various types (email address, facebook, skype, etc.,). So I split into three tables to normalize the types. I can't seem to find out how to properly query and eager load the type of contact. I can get the contacts themselves easy via

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

But for the life of me I can't seem to figure out how to match those contacts to their respective types. Rails did a lot of this under the covers and BOY am I regretting that...

Tables

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

Models

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

Upvotes: 0

Views: 464

Answers (1)

user3875268
user3875268

Reputation: 11

I believe chaining the relationships in the withRelated array should do the trick. Try the following:

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

Upvotes: 1

Related Questions