diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 9dd478a7..8429fdaa 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -819,6 +819,8 @@ RelationDefinition.belongsTo = function (modelFrom, modelTo, params) { keyFrom: fk, keyTo: idName, modelTo: modelTo, + properties: params.properties, + scope: params.scope, options: params.options }); @@ -860,6 +862,8 @@ BelongsTo.prototype.create = function(targetModelData, cb) { targetModelData = {}; } + this.definition.applyProperties(modelInstance, targetModelData || {}); + modelTo.create(targetModelData, function(err, targetModel) { if(!err) { modelInstance[fk] = targetModel[pk]; @@ -873,6 +877,7 @@ BelongsTo.prototype.create = function(targetModelData, cb) { BelongsTo.prototype.build = function(targetModelData) { var modelTo = this.definition.modelTo; + this.definition.applyProperties(this.modelInstance, targetModelData || {}); return new modelTo(targetModelData); }; @@ -911,7 +916,12 @@ BelongsTo.prototype.related = function (refresh, params) { } else if (typeof params === 'function') { // acts as async getter var cb = params; if (cachedValue === undefined) { - modelTo.findById(modelInstance[fk], function (err, inst) { + var query = {where: {}}; + query.where[pk] = modelInstance[fk]; + + this.definition.applyScope(modelInstance, query); + + modelTo.findOne(query, function (err, inst) { if (err) { return cb(err); } @@ -919,7 +929,7 @@ BelongsTo.prototype.related = function (refresh, params) { return cb(null, null); } // Check if the foreign key matches the primary key - if (inst[pk] === modelInstance[fk]) { + if (inst[pk] && inst[pk].toString() === modelInstance[fk].toString()) { self.resetCache(inst); cb(null, inst); } else { @@ -1193,7 +1203,7 @@ HasOne.prototype.related = function (refresh, params) { return cb(null, null); } // Check if the foreign key matches the primary key - if (inst[fk] === modelInstance[pk]) { + if (inst[fk] && inst[fk].toString() === modelInstance[pk].toString()) { self.resetCache(inst); cb(null, inst); } else {