From 90a80705180d003a1e896bc307d3abc1720366dc Mon Sep 17 00:00:00 2001 From: Rashad Date: Mon, 21 Oct 2024 03:01:33 +0530 Subject: [PATCH] Eager loading for titles --- app/Api/ApiEntityListFormatter.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/app/Api/ApiEntityListFormatter.php b/app/Api/ApiEntityListFormatter.php index 23fa8e6ea..2fd9b7c55 100644 --- a/app/Api/ApiEntityListFormatter.php +++ b/app/Api/ApiEntityListFormatter.php @@ -106,6 +106,10 @@ class ApiEntityListFormatter */ public function format(): array { + if ($this->includeRelatedTitles) { + $this->loadRelatedTitles(); + } + $results = []; foreach ($this->list as $item) { @@ -115,6 +119,23 @@ class ApiEntityListFormatter return $results; } + /** + * Eager load the related book and chapter data when needed. + */ + protected function loadRelatedTitles(): void + { + $pages = collect($this->list)->filter(fn($item) => $item instanceof Page); + + foreach ($this->list as $entity) { + if (method_exists($entity, 'book')) { + $entity->load('book'); + } + if ($entity instanceof Page && $entity->chapter_id) { + $entity->load('chapter'); + } + } + } + /** * Format a single entity item to a plain array. */