import {Model} from '../Model' import {HasOneOrMany} from './HasOneOrMany' import {Collection} from '../../../util' import {RelationNotLoadedError} from './Relation' /** * One-to-many relation implementation. */ export class HasMany, T2 extends Model> extends HasOneOrMany> { protected cachedValue?: Collection protected cachedLoaded = false constructor( parent: T, related: T2, foreignKeyOverride?: keyof T & string, localKeyOverride?: keyof T2 & string, ) { super(parent, related, foreignKeyOverride, localKeyOverride) } /** Resolve the result of this relation. */ public get(): Promise> { return this.fetch().collect() } /** Set the value of this relation. */ public setValue(related: Collection): void { this.cachedValue = related.clone() this.cachedLoaded = true } /** Get the value of this relation. */ public getValue(): Collection { if ( !this.cachedValue ) { throw new RelationNotLoadedError() } return this.cachedValue } /** Returns true if the relation has been loaded. */ public isLoaded(): boolean { return this.cachedLoaded } }