Skip to content

Commit 1714347

Browse files
Bart Hijmanssdebacker
Bart Hijmans
authored andcommitted
Added setParents() to eager load the ->parent relation. This allows
1 parent 11bc91d commit 1714347

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/NestableCollection.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,4 +202,26 @@ public function getTotal()
202202
{
203203
return $this->total();
204204
}
205+
206+
/**
207+
* Sets the $item->parent relation for each item in the NestableCollection to be the parent it has in the collection
208+
* so it can be used without querying the database.
209+
*
210+
* @return $this
211+
*/
212+
public function setParents()
213+
{
214+
$this->setParentsRecursive($this);
215+
return $this;
216+
}
217+
218+
protected function setParentsRecursive(&$items, &$parent = null)
219+
{
220+
foreach ($items as $item) {
221+
if ($parent) {
222+
$item->setRelation('parent', $parent);
223+
}
224+
$this->setParentsRecursive($item->items, $item);
225+
}
226+
}
205227
}

0 commit comments

Comments
 (0)