Use the primary key type for the generated foreign key

This commit is contained in:
Raymond Feng 2014-01-21 09:47:32 -08:00
parent 803821e736
commit c374cc89cd
2 changed files with 23 additions and 2 deletions

View File

@ -1430,11 +1430,19 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
// quit if key already defined
if (this.getModelDefinition(className).rawProperties[key]) return;
var defaultType = Number;
if(foreignClassName) {
var foreignModel = this.getModelDefinition(foreignClassName);
var pkName = foreignModel && foreignModel.idName();
if(pkName) {
defaultType = foreignModel.properties[pkName].type;
}
}
if (this.connector.defineForeignKey) {
var cb = function (err, keyType) {
if (err) throw err;
// Add the foreign key property to the data source _models
this.defineProperty(className, key, {type: keyType || Number});
this.defineProperty(className, key, {type: keyType || defaultType});
}.bind(this);
switch (this.connector.defineForeignKey.length) {
case 4:
@ -1447,7 +1455,7 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
}
} else {
// Add the foreign key property to the data source _models
this.defineProperty(className, key, {type: Number});
this.defineProperty(className, key, {type: defaultType});
}
};

View File

@ -510,6 +510,19 @@ describe('Load models with relations', function () {
done();
});
it('should set up foreign key with the correct type', function (done) {
var ds = new DataSource('memory');
var User = ds.define('User', {name: String, id: {type: String, id: true}});
var Post = ds.define('Post', {content: String}, {relations: {user: {type: 'belongsTo', model: 'User'}}});
var fk = Post.definition.properties['userId'];
assert(fk, 'The foreign key should be added');
assert(fk.type === String, 'The foreign key should be the same type as primary key');
assert(Post.relations['user'], 'User relation should be set');
done();
});
it('should set up hasMany and belongsTo relations', function (done) {
var ds = new DataSource('memory');