Start implementation of model relations
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
47
src/orm/model/relation/HasMany.ts
Normal file
47
src/orm/model/relation/HasMany.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user