]> BookStack Code Mirror - bookstack/commitdiff
Eager loading for titles
authorRashad <redacted>
Sun, 20 Oct 2024 21:31:33 +0000 (03:01 +0530)
committerRashad <redacted>
Sun, 20 Oct 2024 21:31:33 +0000 (03:01 +0530)
app/Api/ApiEntityListFormatter.php

index 23fa8e6ea7249274759e5b4fa98cf49b27a50a8a..2fd9b7c5507b4ce8e8713280c78d62dd26c9171e 100644 (file)
@@ -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.
      */