From cc884f70963b9ecc402475d4d92ee4c7ae9ffad0 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Wed, 29 Jul 2020 16:17:30 +0200 Subject: [PATCH] ModelRelation eagerloading: don't make an SQL query when there is nothing to fetch --- src/db/ModelRelation.ts | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/db/ModelRelation.ts b/src/db/ModelRelation.ts index c45d850..0762e8f 100644 --- a/src/db/ModelRelation.ts +++ b/src/db/ModelRelation.ts @@ -82,11 +82,10 @@ export class OneModelRelation extends ModelRel } public async eagerLoad(relations: ModelRelation[]): Promise> { - this.query.where( - this.dbProperties.foreignKey, - relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined), - WhereTest.IN - ); + const ids = relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined); + if (ids.length === 0) return []; + + this.query.where(this.dbProperties.foreignKey, ids, WhereTest.IN); return await this.query.get(); } @@ -136,11 +135,10 @@ export class ManyModelRelation extends ModelRe } public async eagerLoad(relations: ModelRelation[]): Promise> { - this.query.where( - this.dbProperties.foreignKey, - relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined), - WhereTest.IN - ); + const ids = relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined); + if (ids.length === 0) return []; + + this.query.where(this.dbProperties.foreignKey, ids, WhereTest.IN); return await this.query.get(); } @@ -189,10 +187,10 @@ export class ManyThroughModelRelation extends } public async eagerLoad(relations: ModelRelation[]): Promise> { - this.query.where( - `pivot.${this.dbProperties.localPivotKey}`, - relations.map(r => r.getModelID()), - WhereTest.IN); + const ids = relations.map(r => r.getModelID()); + if (ids.length === 0) return []; + + this.query.where(`pivot.${this.dbProperties.localPivotKey}`, ids, WhereTest.IN); this.query.pivot(`pivot.${this.dbProperties.localPivotKey}`, `pivot.${this.dbProperties.foreignPivotKey}`); return await this.query.get(); }