简体   繁体   English

Bookshelf.js渴望加载第三张表

[英]Bookshelf.js Eager Loading Third Table

I'm struggling with Bookshelf.js and I'm hoping someone can lend me a hand. 我在Bookshelf.js方面苦苦挣扎,希望有人可以帮我忙。

I've customers who have contacts of various types (email address, facebook, skype, etc.,). 我的客户有各种类型的联系人(电子邮件地址,facebook,skype等)。 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... Rails做了很多这样的事情,男孩,我很后悔...

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

I believe chaining the relationships in the withRelated array should do the trick. 我相信在withRelated数组中链接关系应该可以解决问题。 Try the following: 请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM