diff --git a/lib/abstract-class.js b/lib/abstract-class.js index 599b4dbb..c70445f5 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -490,20 +490,31 @@ AbstractClass.hasMany = function (anotherClass, params) { AbstractClass.belongsTo = function (anotherClass, params) { var methodName = params.as; var fk = params.foreignKey; - this.schema.defineForeignKey(anotherClass.modelName, fk); - this.prototype[methodName] = function (p, cb) { + this.prototype['__finders__'] = this.prototype['__finders__'] || {} + + 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 this[fk] = p.id; this.cachedRelations[methodName] = p; } else if (typeof p === 'function') { // acts as async getter - this.find(this[fk], function (err, obj) { - if (err) return p(err); - this.cachedRelations[methodName] = obj; - }.bind(this)); + this.__finders__[methodName](this[fk],p); } 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) {