Merge pull request #27 from patrickotoole/master

Modified belongsTo method
This commit is contained in:
1602 2012-02-21 13:47:40 -08:00
commit 61cad1c89e
1 changed files with 18 additions and 7 deletions

View File

@ -490,20 +490,31 @@ AbstractClass.hasMany = function (anotherClass, params) {
AbstractClass.belongsTo = function (anotherClass, params) { AbstractClass.belongsTo = function (anotherClass, params) {
var methodName = params.as; var methodName = params.as;
var fk = params.foreignKey; var fk = params.foreignKey;
this.schema.defineForeignKey(anotherClass.modelName, fk); this.prototype['__finders__'] = this.prototype['__finders__'] || {}
this.prototype[methodName] = function (p, cb) {
this.prototype['__finders__'][methodName] = function (id, cb) {
anotherClass.find(id, function (err,inst) {
if (err) return cb(err);
if (inst[fk] === this.id) {
cb(null, inst);
} else {
cb(new Error('Permission denied'));
}
}.bind(this));
}
this.prototype[methodName] = function (p) {
if (p instanceof AbstractClass) { // acts as setter if (p instanceof AbstractClass) { // acts as setter
this[fk] = p.id; this[fk] = p.id;
this.cachedRelations[methodName] = p; this.cachedRelations[methodName] = p;
} else if (typeof p === 'function') { // acts as async getter } else if (typeof p === 'function') { // acts as async getter
this.find(this[fk], function (err, obj) { this.__finders__[methodName](this[fk],p);
if (err) return p(err);
this.cachedRelations[methodName] = obj;
}.bind(this));
} else if (!p) { // acts as sync getter } else if (!p) { // acts as sync getter
return this.cachedRelations[methodName] || this[fk]; return this[fk];
} }
}; };
console.log(this.prototype);
}; };
AbstractClass.scope = function (name, params) { AbstractClass.scope = function (name, params) {