From c374cc89cdc4381b7edc29565ffc8a3a247a7719 Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Tue, 21 Jan 2014 09:47:32 -0800 Subject: [PATCH] Use the primary key type for the generated foreign key --- lib/datasource.js | 12 ++++++++++-- test/loopback-dl.test.js | 13 +++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/datasource.js b/lib/datasource.js index f3a239ca..425796cb 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -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}); } }; diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index 81b7278c..65c0f892 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -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');