diff --git a/src/db/ModelRelation.ts b/src/db/ModelRelation.ts index 027f178..baa9a0e 100644 --- a/src/db/ModelRelation.ts +++ b/src/db/ModelRelation.ts @@ -53,6 +53,18 @@ export default abstract class ModelRelation[]): Promise>; public abstract async populate(models: ModelQueryResult): Promise; + + public async count(): Promise { + const models = await this.get(); + if (Array.isArray(models)) return models.length; + else return models !== null ? 1 : 0; + } + + public async has(model: O): Promise { + const models = await this.get(); + if (Array.isArray(models)) return models.find(m => m.equals(model)) !== undefined; + else return models && models.equals(model); + } } export class OneModelRelation extends ModelRelation { @@ -154,7 +166,6 @@ export class ManyModelRelation extends ModelRe public async populate(models: ModelQueryResult): Promise { this.cachedModels = models.filter(m => m[this.dbProperties.foreignKey] === this.getModelID()); } - } export class ManyThroughModelRelation extends ModelRelation { @@ -212,10 +223,8 @@ export class ManyThroughModelRelation extends .map(p => p[`pivot.${this.dbProperties.foreignPivotKey}`]); this.cachedModels = models.filter(m => ids.indexOf(m[this.dbProperties.foreignKey]) >= 0); } - } - export type QueryModifier = (query: ModelQuery) => ModelQuery; export type ModelFilter = (model: O) => boolean | Promise;