我正在与 Bookshelf.js 作斗争,希望有人能帮我一把。
我的客户拥有各种类型的联系人(电子邮件地址、Facebook、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());
})
关于javascript - Bookshelf.js 预加载第三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493811/