From 68ff977bcc4171f9cc4525feef6c8f704c97dacf Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Wed, 2 Sep 2020 11:55:38 +0200 Subject: [PATCH] ModelQuery: fix model instantiation field conflict for jointures --- src/db/ModelQuery.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/db/ModelQuery.ts b/src/db/ModelQuery.ts index ff0d386..ade72e3 100644 --- a/src/db/ModelQuery.ts +++ b/src/db/ModelQuery.ts @@ -29,7 +29,7 @@ export default class ModelQuery { private readonly type: QueryType; private readonly factory: ModelFactory; private readonly table: string; - private readonly fields: (string | SelectFieldValue | UpdateFieldValue)[]; + private fields: (string | SelectFieldValue | UpdateFieldValue)[]; private _leftJoin?: string; private _leftJoinOn: WhereFieldValue[] = []; private _where: WhereFieldValue[] = []; @@ -90,7 +90,10 @@ export default class ModelQuery { public toString(final: boolean = false): string { let query = ''; - if (this._pivot) this.fields.push(...this._pivot); + if (this._pivot) { + this.fields = this.fields.map(f => this.table + '.' + f); + this.fields.push(...this._pivot); + } let fields = this.fields.join(','); @@ -170,15 +173,20 @@ export default class ModelQuery { } for (const result of queryResult.results) { - const model = this.factory.create(result); + const modelData: any = {}; + for (const field of Object.keys(result)) { + modelData[field.split('.')[1] || field] = result[field]; + } + + const model = this.factory.create(modelData); models.push(model); if (this._pivot) { - const obj: any = {}; + const pivotData: any = {}; for (const field of this._pivot) { - obj[field] = result[field.split('.')[1]]; + pivotData[field] = result[field.split('.')[1]]; } - models.pivot!.push(obj); + models.pivot!.push(pivotData); } // Eager loading init map