From b88f4e1b64170041a738c2f4a9dd3cb55c22a017 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Mon, 7 Sep 2020 14:02:43 +0200 Subject: [PATCH] ModelRelation: deduplicate eagerloaded models --- src/db/ModelRelation.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/db/ModelRelation.ts b/src/db/ModelRelation.ts index 12ab91e..120ad05 100644 --- a/src/db/ModelRelation.ts +++ b/src/db/ModelRelation.ts @@ -70,7 +70,9 @@ export default abstract class ModelRelation[], subRelations: string[] = []): Promise> { - const ids = relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined); + const ids = relations.map(r => r.getModelID()) + .filter(id => id !== null && id !== undefined) + .reduce((array: O[], val) => val in array ? array : [...array, val], []); if (ids.length === 0) return []; const query = this.makeQuery(); @@ -80,7 +82,8 @@ export default abstract class ModelRelation): Promise { - this.cachedModels = models.filter(m => m[this.dbProperties.foreignKey] === this.getModelID()); + this.cachedModels = models.filter(m => m[this.dbProperties.foreignKey] === this.getModelID()) + .reduce((array: O[], val) => array.find(v => v.equals(val)) ? array : [...array, val], []); } public async count(): Promise { @@ -177,7 +180,8 @@ export class ManyThroughModelRelation extends } public async eagerLoad(relations: ModelRelation[], subRelations: string[] = []): Promise> { - const ids = relations.map(r => r.getModelID()); + const ids = relations.map(r => r.getModelID()) + .reduce((array: O[], val) => val in array ? array : [...array, val], []); if (ids.length === 0) return []; const query = this.makeQuery(); @@ -191,7 +195,8 @@ export class ManyThroughModelRelation extends const ids = models.pivot! .filter(p => p[`pivot.${this.dbProperties.localPivotKey}`] === this.getModelID()) .map(p => p[`pivot.${this.dbProperties.foreignPivotKey}`]); - this.cachedModels = models.filter(m => ids.indexOf(m[this.dbProperties.foreignKey]) >= 0); + this.cachedModels = models.filter(m => ids.indexOf(m[this.dbProperties.foreignKey]) >= 0) + .reduce((array: O[], val) => array.find(v => v.equals(val)) ? array : [...array, val], []); } }