Skip to content

Commit 90a8070

Browse files
committed
Eager loading for titles
1 parent 3e656ef commit 90a8070

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

app/Api/ApiEntityListFormatter.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ public function withRelatedTitles(): self
106106
*/
107107
public function format(): array
108108
{
109+
if ($this->includeRelatedTitles) {
110+
$this->loadRelatedTitles();
111+
}
112+
109113
$results = [];
110114

111115
foreach ($this->list as $item) {
@@ -115,6 +119,23 @@ public function format(): array
115119
return $results;
116120
}
117121

122+
/**
123+
* Eager load the related book and chapter data when needed.
124+
*/
125+
protected function loadRelatedTitles(): void
126+
{
127+
$pages = collect($this->list)->filter(fn($item) => $item instanceof Page);
128+
129+
foreach ($this->list as $entity) {
130+
if (method_exists($entity, 'book')) {
131+
$entity->load('book');
132+
}
133+
if ($entity instanceof Page && $entity->chapter_id) {
134+
$entity->load('chapter');
135+
}
136+
}
137+
}
138+
118139
/**
119140
* Format a single entity item to a plain array.
120141
*/

0 commit comments

Comments
 (0)