2016-07-21 6 views
0

私はBookshelf.jsに苦労しています。誰かが私に手を貸してくれることを願っています。Bookshelf.js Eager Loading Thirdテーブル

私はさまざまな種類の連絡先(メールアドレス、Facebook、Skypeなど)を持っている顧客を持っています。そこで、型を正規化するために3つのテーブルに分割しました。私は適切に質問して熱心に接触のタイプを読み込む方法を見つけることができないようです。

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

私の人生の中で、私はこれらの連絡先をそれぞれの種類に合わせる方法を見つけることができないようです。 Railsはこれの多くは、カバーやBOYの下で、私はwithRelated中関係の連鎖信じる

テーブル

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

モデル

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

答えて

1

...ことを後悔していませんでした配列はトリックを行う必要があります。以下を試してください:

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