From b7bfb3e153e155cb2533f515c8c71676af55fe7a Mon Sep 17 00:00:00 2001 From: garrettmills Date: Thu, 25 Nov 2021 16:39:17 -0600 Subject: [PATCH] Model: fix eager-loaded relation loading from static query --- src/orm/model/Model.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/orm/model/Model.ts b/src/orm/model/Model.ts index 504e51d..2e36c34 100644 --- a/src/orm/model/Model.ts +++ b/src/orm/model/Model.ts @@ -174,10 +174,24 @@ export abstract class Model> extends AppClass implements Bus builder.field(field.databaseKey) }) - for ( const relation of this.prototype.with ) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - builder.with(relation) + if ( Array.isArray(this.prototype.with) ) { + // Try to get the eager-loaded relations statically, if possible + for (const relation of this.prototype.with) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + builder.with(relation) + } + } else if ( this.constructor.length < 1 ) { + // Otherwise, if we can instantiate the model without any arguments, + // do that and get the eager-loaded relations directly. + const inst = Container.getContainer().make>(this) + if ( Array.isArray(inst.with) ) { + for (const relation of inst.with) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + builder.with(relation) + } + } } builder.withScopes(this.prototype.scopes)