Merge pull request #394 from clarkbw/hasManyThroughKeyThrough

hasMany through doesn't set the through key value
This commit is contained in:
Raymond Feng 2015-02-16 22:45:06 -08:00
commit a44e45b30a
3 changed files with 24 additions and 14 deletions

View File

@ -6,6 +6,7 @@ var util = require('util');
var async = require('async');
var utils = require('./utils');
var i8n = require('inflection');
var _ = require('lodash');
var defineScope = require('./scope.js').defineScope;
var mergeQuery = utils.mergeQuery;
var ModelBaseClass = require('./model.js');
@ -468,20 +469,14 @@ util.inherits(ReferencesMany, Relation);
/*!
* Find the relation by foreign key
* @param {*} foreignKey The foreign key
* @returns {Object} The relation object
* @returns {Array} The array of matching relation objects
*/
function findBelongsTo(modelFrom, modelTo, keyTo) {
var relations = modelFrom.relations;
var keys = Object.keys(relations);
for (var k = 0; k < keys.length; k++) {
var rel = relations[keys[k]];
if (rel.type === RelationTypes.belongsTo &&
rel.modelTo === modelTo &&
(keyTo === undefined || rel.keyTo === keyTo)) {
return rel.keyFrom;
}
}
return null;
return _.pluck(_.filter(modelFrom.relations, function (rel) {
return (rel.type === RelationTypes.belongsTo &&
rel.modelTo === modelTo &&
(keyTo === undefined || rel.keyTo === keyTo));
}), 'keyFrom');
}
/*!
@ -833,10 +828,12 @@ var throughKeys = function(definition) {
} else {
var fk2 = definition.keyThrough;
}
} else if (definition.modelFrom === definition.modelTo) {
return findBelongsTo(modelThrough, definition.modelTo, pk2);
} else {
var fk1 = findBelongsTo(modelThrough, definition.modelFrom,
definition.keyFrom);
var fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2);
definition.keyFrom)[0];
var fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2)[0];
}
return [fk1, fk2];
}

View File

@ -30,6 +30,7 @@
"async": "^0.9.0",
"debug": "^2.1.1",
"inflection": "^1.6.0",
"lodash": "~3.0.1",
"loopback-connector": "1.x",
"qs": "^2.3.3",
"traverse": "^0.6.6"

View File

@ -690,6 +690,18 @@ describe('relations', function () {
});
});
it('should set the keyThrough and the foreignKey', function (done) {
var user = new User({id: 1});
var user2 = new User({id: 2});
user.following.add(user2, function (err, f) {
should.not.exist(err);
should.exist(f);
f.followeeId.should.equal(user2.id);
f.followerId.should.equal(user.id);
done();
});
});
it('can determine the collect via keyThrough for each side', function () {
var user = new User({id: 1});
var scope1 = user.followers._scope;