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.
lib/src/orm/model/relation/HasMany.ts

48 lines
1.3 KiB

import {Model} from '../Model'
import {HasOneOrMany} from './HasOneOrMany'
import {Collection} from '../../../util'
import {RelationNotLoadedError} from './Relation'
/**
* One-to-many relation implementation.
*/
export class HasMany<T extends Model<T>, T2 extends Model<T2>> extends HasOneOrMany<T, T2, Collection<T2>> {
protected cachedValue?: Collection<T2>
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<Collection<T2>> {
return this.fetch().collect()
}
/** Set the value of this relation. */
public setValue(related: Collection<T2>): void {
this.cachedValue = related.clone()
this.cachedLoaded = true
}
/** Get the value of this relation. */
public getValue(): Collection<T2> {
if ( !this.cachedValue ) {
throw new RelationNotLoadedError()
}
return this.cachedValue
}
/** Returns true if the relation has been loaded. */
public isLoaded(): boolean {
return this.cachedLoaded
}
}