Implement scope/properties for BelongsTo (+ fix foreign key matching)

This commit is contained in:
Fabien Franzen 2014-07-22 22:09:29 +02:00
parent fe14a0c835
commit bc4076f35e
1 changed files with 13 additions and 3 deletions

View File

@ -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 {