import {Model} from './Model' import {AbstractBuilder} from '../builder/AbstractBuilder' import {AbstractResultIterable} from '../builder/result/AbstractResultIterable' import {Instantiable, StaticClass} from '../../di' import {ModelResultIterable} from './ModelResultIterable' import {Collection} from '../../util' import {ConstraintOperator, ModelKey, ModelKeys} from '../types' import {EscapeValue} from '../dialect/SQLDialect' /** * Implementation of the abstract builder whose results yield instances of a given Model, `T`. */ export class ModelBuilder> extends AbstractBuilder { constructor( /** The model class that is created for results of this query. */ protected readonly ModelClass: StaticClass & Instantiable, ) { super() } public getNewInstance(): AbstractBuilder { return this.app().make>(ModelBuilder) } public getResultIterable(): AbstractResultIterable { return this.app().make>(ModelResultIterable, this, this.registeredConnection, this.ModelClass) } /** * Apply a WHERE...IN... constraint on the primary key of the model. * @param keys */ public whereKey(keys: ModelKeys): this { return this.whereIn( this.ModelClass.qualifyKey(), this.normalizeModelKeys(keys), ) } /** * Apply a where constraint on the column corresponding the the specified * property on the model. * @param propertyName * @param operator * @param operand */ public whereProperty(propertyName: string, operator: ConstraintOperator, operand?: EscapeValue): this { return this.where( this.ModelClass.propertyToColumn(propertyName), operator, operand, ) } /** * Given some format of keys of the model, try to normalize them to a flat array. * @param keys * @protected */ protected normalizeModelKeys(keys: ModelKeys): ModelKey[] { if ( Array.isArray(keys) ) { return keys } else if ( keys instanceof Collection ) { return keys.all() } return [keys] } }