You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
daton/orm/src/model/ModelResultOperator.ts

55 lines
2.0 KiB

import ResultOperator from '../builder/type/result/ResultOperator.ts'
import {Model} from './Model.ts'
import {Injectable} from '../../../di/src/decorator/Injection.ts'
import {QueryRow} from '../db/types.ts'
import Instantiable from '../../../di/src/type/Instantiable.ts'
import {make} from '../../../di/src/global.ts'
import ConnectionExecutable from '../builder/type/ConnectionExecutable.ts'
import {Collection} from '../../../lib/src/collection/Collection.ts'
import {ModelSelect} from './query/ModelSelect.ts'
@Injectable()
export default class ModelResultOperator<T extends Model<T>> extends ResultOperator<T> {
constructor(
protected ModelClass: Instantiable<T>,
) {
super()
}
inflate_row(row: QueryRow): T {
return make(this.ModelClass).assume_from_source(row)
}
deflate_row(item: T): QueryRow {
return item.to_row()
}
public async process_eager_loads<T2>(query: ConnectionExecutable<T2>, results: Collection<T>) {
if ( query instanceof ModelSelect ) {
const eagers = query.eager_relations
const model = new this.ModelClass()
for ( const full_rel_name of eagers ) {
const rel_name = full_rel_name.split('.')[0]
const child_eagers = eagers.filter((x: string) => x.startsWith(`${rel_name}.`)).map((x: string) => {
return x.split('.').slice(1).join('.')
})
const relation = model.get_relation(rel_name)
const select = await relation.build_eager_query(query, results)
for ( const child_eager of child_eagers ) {
select.with(child_eager)
}
const all_related = await select.results()
results.each(result => {
const result_relation = result.get_relation(rel_name)
const result_related = result_relation.match_results(all_related as any)
result_relation.set_value(result_related as any)
})
}
}
}
}