Bookshelf.js渴望装载第三张桌子

Bookshelf.js Eager Loading Third Table

本文关键字:三张 渴望 js Bookshelf      更新时间:2023-09-26

我正在与Bookshelf.js作斗争,我希望有人能帮我一把。

我的客户有各种类型的联系人(电子邮件地址、脸书、skype等)。因此,我将其分为三个表来规范类型。我似乎找不到如何正确查询和加载联系人类型。我可以通过轻松获取联系人

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

但就我的一生而言,我似乎不知道如何将这些联系人与他们各自的类型相匹配。Rails在幕后做了很多这样的事情,男孩,我很后悔。。。

表格

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

我认为将withRelated数组中的关系链接起来就可以了。尝试以下操作:

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