Merge pull request #27 from patrickotoole/master
Modified belongsTo method
This commit is contained in:
commit
61cad1c89e
|
@ -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) {
|
||||
|
|
Loading…
Reference in New Issue