Support define fk with class name

This commit is contained in:
Anatoliy Chakkaev 2013-04-22 16:22:14 +04:00 committed by Raymond Feng
parent 8099f7edf2
commit 23004c12c1
2 changed files with 14 additions and 5 deletions

View File

@ -124,7 +124,7 @@ Model.hasMany = function hasMany(anotherClass, params) {
if (!params.through) {
// obviously, anotherClass should have attribute called `fk`
anotherClass.schema.defineForeignKey(anotherClass.modelName, fk);
anotherClass.schema.defineForeignKey(anotherClass.modelName, fk, this.modelName);
}
function find(id, cb) {
@ -201,7 +201,7 @@ Model.belongsTo = function (anotherClass, params) {
multiple: false
};
this.schema.defineForeignKey(this.modelName, fk);
this.schema.defineForeignKey(this.modelName, fk, anotherClass.modelName);
this.prototype['__finders__'] = this.prototype['__finders__'] || {};
this.prototype['__finders__'][methodName] = function (id, cb) {

View File

@ -461,15 +461,24 @@ Schema.prototype.tableName = function (modelName) {
* @param {String} className
* @param {String} key - name of key field
*/
Schema.prototype.defineForeignKey = function defineForeignKey(className, key) {
Schema.prototype.defineForeignKey = function defineForeignKey(className, key, foreignClassName) {
// quit if key already defined
if (this.definitions[className].properties[key]) return;
if (this.adapter.defineForeignKey) {
this.adapter.defineForeignKey(className, key, function (err, keyType) {
var cb = function (err, keyType) {
if (err) throw err;
this.definitions[className].properties[key] = {type: keyType};
}.bind(this));
}.bind(this);
switch (this.adapter.defineForeignKey.length) {
case 4:
this.adapter.defineForeignKey(className, key, foreignClassName, cb);
break;
default:
case 3:
this.adapter.defineForeignKey(className, key, cb);
break;
}
} else {
this.definitions[className].properties[key] = {type: Number};
}