Create belongs_to_one and belongs_to_many inverse helpers

This commit is contained in:
garrettmills
2020-08-16 09:46:17 -05:00
parent 81906b02bc
commit bd1c221e36
3 changed files with 45 additions and 1 deletions

View File

@@ -17,6 +17,7 @@ import Instantiable from '../../../di/src/type/Instantiable.ts'
import {HasMany} from './relation/HasMany.ts'
import {ModelSelect} from "./query/ModelSelect.ts";
import {Relation} from "./relation/Relation.ts";
import {HasOneOrMany} from "./relation/HasOneOrMany.ts";
// TODO separate read/write connections
// TODO manual dirty flags
@@ -979,6 +980,38 @@ abstract class Model<T extends Model<T>> extends Builder<T> implements Rehydrata
return new HasMany(this as any, new related() as any, foreign_key, local_key)
}
/**
* Defines the inverse of a has one or many relation.
* @param {typeof Model} related
* @param {string} relation_name - the name of the relation function on the inverse
*/
public belongs_to_one<T extends Model<T>>(related: Instantiable<T>, relation_name: string) {
const related_inst = new related()
const relation = related_inst.get_relation(relation_name)
if ( !(relation instanceof HasOneOrMany) ) {
throw new TypeError(`Cannot create belongs to one relation. Inverse relation must be has one or many.`)
}
return new HasOne(this as any, related_inst, relation.local_key, relation.foreign_key)
}
/**
* Defines the inverse of a has one or many relation.
* @param {typeof Model} related
* @param {string} relation_name - the name of the relation function on the inverse
*/
public belongs_to_many<T extends Model<T>>(related: Instantiable<T>, relation_name: string) {
const related_inst = new related()
const relation = related_inst.get_relation(relation_name)
if ( !(relation instanceof HasOneOrMany) ) {
throw new TypeError(`Cannot create belongs to one relation. Inverse relation must be has one or many.`)
}
return new HasMany(this as any, related_inst, relation.local_key, relation.foreign_key)
}
public get_relation<T2 extends Model<T2>>(name: string): Relation<T, T2> {
// @ts-ignore
const rel: any = this[name]()