From 5c35d2c03d0e58e193c1c32935d8715782ef3966 Mon Sep 17 00:00:00 2001 From: Joshua Hulpiau Date: Mon, 19 Oct 2020 14:37:25 +0200 Subject: [PATCH] Fix for when a through table has multiple associations --- lib/waterline/methods/add-to-collection.js | 15 ++++++++++----- lib/waterline/methods/replace-collection.js | 15 ++++++++++----- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/lib/waterline/methods/add-to-collection.js b/lib/waterline/methods/add-to-collection.js index eb3ce3e7e..fd1fa2190 100644 --- a/lib/waterline/methods/add-to-collection.js +++ b/lib/waterline/methods/add-to-collection.js @@ -349,11 +349,16 @@ module.exports = function addToCollection(/* targetRecordIds, collectionAttrName // through table mapping that was generated by Waterline-Schema. else if (_.has(Object.getPrototypeOf(WLChild), 'throughTable')) { childReference = WLChild.throughTable[WLModel.identity + '.' + query.collectionAttrName]; - _.each(WLChild.throughTable, function(rhs, key) { - if (key !== WLModel.identity + '.' + query.collectionAttrName) { - parentReference = rhs; - } - }); + + parentReference = WLModel.identity; + + // this code assumed that there would be only 2 associations on the through table + // but in some projects there are multiple + // _.each(WLChild.throughTable, function(rhs, key) { + // if (key !== WLModel.identity + '.' + query.collectionAttrName) { + // parentReference = rhs; + // } + // }); } // Find the child reference in a junction table diff --git a/lib/waterline/methods/replace-collection.js b/lib/waterline/methods/replace-collection.js index fd9679041..0cd84805c 100644 --- a/lib/waterline/methods/replace-collection.js +++ b/lib/waterline/methods/replace-collection.js @@ -358,11 +358,16 @@ module.exports = function replaceCollection(/* targetRecordIds?, collectionAttrN // through table mapping that was generated by Waterline-Schema. else if (_.has(Object.getPrototypeOf(WLChild), 'throughTable')) { childReference = WLChild.throughTable[WLModel.identity + '.' + query.collectionAttrName]; - _.each(WLChild.throughTable, function(rhs, key) { - if (key !== WLModel.identity + '.' + query.collectionAttrName) { - parentReference = rhs; - } - }); + + // should be safe to assume that the parentReference is indeed the main model here + parentReference = WLModel.identity; + + // this code assumed that there would be only 2 associations on the through table (as stated above) + // _.each(WLChild.throughTable, function(rhs, key) { + // if (key !== WLModel.identity + '.' + query.collectionAttrName) { + // parentReference = rhs; + // } + // }); }//>-