ModelQuery: fix model instantiation field conflict for jointures

This commit is contained in:
Alice Gaudon 2020-09-02 11:55:38 +02:00
parent 3e13ba0202
commit 68ff977bcc

View File

@ -29,7 +29,7 @@ export default class ModelQuery<M extends Model> {
private readonly type: QueryType; private readonly type: QueryType;
private readonly factory: ModelFactory<M>; private readonly factory: ModelFactory<M>;
private readonly table: string; private readonly table: string;
private readonly fields: (string | SelectFieldValue | UpdateFieldValue)[]; private fields: (string | SelectFieldValue | UpdateFieldValue)[];
private _leftJoin?: string; private _leftJoin?: string;
private _leftJoinOn: WhereFieldValue[] = []; private _leftJoinOn: WhereFieldValue[] = [];
private _where: WhereFieldValue[] = []; private _where: WhereFieldValue[] = [];
@ -90,7 +90,10 @@ export default class ModelQuery<M extends Model> {
public toString(final: boolean = false): string { public toString(final: boolean = false): string {
let query = ''; 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(','); let fields = this.fields.join(',');
@ -170,15 +173,20 @@ export default class ModelQuery<M extends Model> {
} }
for (const result of queryResult.results) { 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); models.push(model);
if (this._pivot) { if (this._pivot) {
const obj: any = {}; const pivotData: any = {};
for (const field of this._pivot) { 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 // Eager loading init map