From 90e97354fcf20784ddcb04d51a6577f8ed2bdf86 Mon Sep 17 00:00:00 2001 From: Zao Soula Date: Sat, 14 Dec 2024 19:58:24 +0100 Subject: [PATCH] feat(preloader): add preloadOnce to preload a relationship only once --- src/orm/preloader/index.ts | 12 ++++++++++++ src/types/model.ts | 2 ++ src/types/relations.ts | 3 +++ 3 files changed, 17 insertions(+) diff --git a/src/orm/preloader/index.ts b/src/orm/preloader/index.ts index 2850bd0c..d942c823 100644 --- a/src/orm/preloader/index.ts +++ b/src/orm/preloader/index.ts @@ -128,6 +128,18 @@ export class Preloader implements PreloaderContract { return this.load(name, callback) } + /** + * Define a relationship to preload, but only if they are not + * already preloaded + */ + preloadOnce(name: any): this { + if (!this.preloads[name]) { + return this.load(name) + } + + return this + } + /** * Toggle query debugging */ diff --git a/src/types/model.ts b/src/types/model.ts index 0b41283f..7052c993 100644 --- a/src/types/model.ts +++ b/src/types/model.ts @@ -42,6 +42,7 @@ import { WithAggregate, WithCount, PreloadWithoutCallback, + PreloadOnce, } from './relations.js' /** @@ -481,6 +482,7 @@ export interface ModelQueryBuilderContract, this> + preloadOnce: PreloadOnce, this> /** * Aggregates diff --git a/src/types/relations.ts b/src/types/relations.ts index 3291aff3..c96b9291 100644 --- a/src/types/relations.ts +++ b/src/types/relations.ts @@ -1065,6 +1065,9 @@ export interface PreloadWithoutCallback { >(relation: Name): Builder } +export interface PreloadOnce + extends PreloadWithoutCallback {} + /** * Shape of the preloader to preload relationships */