diff --git a/lib/abstract-class.js b/lib/abstract-class.js index d5bc85c4..4521dc52 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -489,20 +489,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) {