ModelRelation eagerloading: don't make an SQL query when there is nothing to fetch

This commit is contained in:
Alice Gaudon 2020-07-29 16:17:30 +02:00
parent 8ca4c1a791
commit cc884f7096

View File

@ -82,11 +82,10 @@ export class OneModelRelation<S extends Model, O extends Model> extends ModelRel
} }
public async eagerLoad(relations: ModelRelation<S, O, O | null>[]): Promise<ModelQueryResult<O>> { public async eagerLoad(relations: ModelRelation<S, O, O | null>[]): Promise<ModelQueryResult<O>> {
this.query.where( const ids = relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined);
this.dbProperties.foreignKey, if (ids.length === 0) return [];
relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined),
WhereTest.IN this.query.where(this.dbProperties.foreignKey, ids, WhereTest.IN);
);
return await this.query.get(); return await this.query.get();
} }
@ -136,11 +135,10 @@ export class ManyModelRelation<S extends Model, O extends Model> extends ModelRe
} }
public async eagerLoad(relations: ModelRelation<S, O, O[]>[]): Promise<ModelQueryResult<O>> { public async eagerLoad(relations: ModelRelation<S, O, O[]>[]): Promise<ModelQueryResult<O>> {
this.query.where( const ids = relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined);
this.dbProperties.foreignKey, if (ids.length === 0) return [];
relations.map(r => r.getModelID()).filter(id => id !== null && id !== undefined),
WhereTest.IN this.query.where(this.dbProperties.foreignKey, ids, WhereTest.IN);
);
return await this.query.get(); return await this.query.get();
} }
@ -189,10 +187,10 @@ export class ManyThroughModelRelation<S extends Model, O extends Model> extends
} }
public async eagerLoad(relations: ModelRelation<S, O, O[]>[]): Promise<ModelQueryResult<O>> { public async eagerLoad(relations: ModelRelation<S, O, O[]>[]): Promise<ModelQueryResult<O>> {
this.query.where( const ids = relations.map(r => r.getModelID());
`pivot.${this.dbProperties.localPivotKey}`, if (ids.length === 0) return [];
relations.map(r => r.getModelID()),
WhereTest.IN); this.query.where(`pivot.${this.dbProperties.localPivotKey}`, ids, WhereTest.IN);
this.query.pivot(`pivot.${this.dbProperties.localPivotKey}`, `pivot.${this.dbProperties.foreignPivotKey}`); this.query.pivot(`pivot.${this.dbProperties.localPivotKey}`, `pivot.${this.dbProperties.foreignPivotKey}`);
return await this.query.get(); return await this.query.get();
} }