Skip to content

Commit

Permalink
Fix withRelated not always grouping properly for binary IDs
Browse files Browse the repository at this point in the history
- When grouped relations, convert Buffers to hex strings to use as the mapping key
  • Loading branch information
6utt3rfly committed Nov 18, 2018
1 parent fc66733 commit 8b00040
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions lib/relation.js
Expand Up @@ -374,20 +374,21 @@ const Relation = RelationBase.extend({
if (this.isJoined()) related = this.parsePivot(related);

// Group all of the related models for easier association with their parent models.
const groupingKey = (key) => (_.isBuffer(key) ? Buffer.toString() : key);
const grouped = _.groupBy(related, (m) => {
let key;
if (m.pivot) {
if (this.isInverse() && this.isThrough()) {
return this.isThroughForeignKeyTargeted() ? m.pivot.get(this.throughForeignKeyTarget) : m.pivot.id;
key = this.isThroughForeignKeyTargeted() ? m.pivot.get(this.throughForeignKeyTarget) : m.pivot.id;
} else {
key = m.pivot.get(this.key('foreignKey'));
}

return m.pivot.get(this.key('foreignKey'));
}

if (this.isInverse()) {
return this.isForeignKeyTargeted() ? m.get(this.foreignKeyTarget) : m.id;
} else if (this.isInverse()) {
key = this.isForeignKeyTargeted() ? m.get(this.foreignKeyTarget) : m.id;
} else {
key = m.get(this.key('foreignKey'));
}

return m.get(this.key('foreignKey'));
return groupingKey(key);
});

// Loop over the `parentModels` and attach the grouped sub-models,
Expand All @@ -396,11 +397,11 @@ const Relation = RelationBase.extend({
let groupedKey;
if (!this.isInverse()) {
const parsedKey = Object.keys(model.parse({[this.parentIdAttribute]: null}))[0];
groupedKey = model.get(parsedKey);
groupedKey = groupingKey(model.get(parsedKey));
} else {
const keyColumn = this.key(this.isThrough() ? 'throughForeignKey' : 'foreignKey');
const formatted = model.format(_.clone(model.attributes));
groupedKey = formatted[keyColumn];
groupedKey = groupingKey(formatted[keyColumn]);
}
if (groupedKey != null) {
const relation = (model.relations[relationName] = this.relatedInstance(grouped[groupedKey], options));
Expand Down

0 comments on commit 8b00040

Please sign in to comment.