是否可以在 Bookshelf.js 中指定用于数据关系的字段
Is it possible to specify which field to use for data relation in Bookshelf.js
我目前遇到一个问题,我想指定书架模型使用哪个字段来建立数据关系。
好像总是用模型的id(主键)table;据我所知,只能为关系设置列,而不能从模型中使用。
例如:
var StopsWithCustomer = bookshelf.Model.extend({
tableName: 'stops',
customers: function () {
return this.hasOne(customerWithStop, 'id');
}
});
它必须匹配列 id 上的 customerWithStop,但它必须使用 'stops' 中的列 customer_id 来建立这种关系;有什么办法可以指定吗?
除了tableName
Bookshelf.js还提供了idAttribute
属性。这将允许您覆盖 Bookshelf.js' id
默认值。
请注意关系的第二个参数(如您的 hasOne()
)是外键,而不是目标的主键。
示例:
var Language = bookshelf.Model.extend({
tableName: 'languages',
idAttribute: 'languageid'
});
var Post = bookshelf.Model.extend({
tableName: 'posts',
idAttribute: 'postid',
Language: function() {
return this.belongsTo(Language,'languageid');
}
});
我目前遇到一个问题,我想指定书架模型使用哪个字段来建立数据关系。
好像总是用模型的id(主键)table;据我所知,只能为关系设置列,而不能从模型中使用。
例如:
var StopsWithCustomer = bookshelf.Model.extend({
tableName: 'stops',
customers: function () {
return this.hasOne(customerWithStop, 'id');
}
});
它必须匹配列 id 上的 customerWithStop,但它必须使用 'stops' 中的列 customer_id 来建立这种关系;有什么办法可以指定吗?
除了tableName
Bookshelf.js还提供了idAttribute
属性。这将允许您覆盖 Bookshelf.js' id
默认值。
请注意关系的第二个参数(如您的 hasOne()
)是外键,而不是目标的主键。
示例:
var Language = bookshelf.Model.extend({
tableName: 'languages',
idAttribute: 'languageid'
});
var Post = bookshelf.Model.extend({
tableName: 'posts',
idAttribute: 'postid',
Language: function() {
return this.belongsTo(Language,'languageid');
}
});