我喜欢2张桌子;
Property {id, name, address_id}
Address {id, city, country, add_line_1, ...}
我通过address_id将Property链接到Address。 如何配置Bookshelf模型以通过address_id加载具有相关地址的Property 我尝试过喜欢的东西;
PROPERTY = bookshelf.Model.extend({
tableName: 'PROPERTY',
address: function() {
return this.hasOne(ADDRESS, 'address_id');
}
});
ADDRESS = bookshelf.Model.extend({
tableName: 'ADDRESS',
property: function() {
return this.belongsTo(PROPERTY);
}
});
错误:" where子句"中的未知ADDRESS.address_id;
答案 0 :(得分:0)
从documentation hasOne()
期望外键在其他表上。因此,请尝试将模型更改为:
PROPERTY = bookshelf.Model.extend({
tableName: 'PROPERTY',
address: function() {
return this.belongsTo(ADDRESS, 'address_id');
}
});
ADDRESS = bookshelf.Model.extend({
tableName: 'ADDRESS',
property: function() {
return this.hasOne(PROPERTY);
}
});
并使用示例查询:
PROPERTY.fetchAll({withRelated:'address'}).then((a)=>
{console.log(a.toJSON())});