-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTreeCollection.php
59 lines (51 loc) · 1.58 KB
/
TreeCollection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php namespace October\Rain\Database;
use Illuminate\Database\Eloquent\Collection as CollectionBase;
/**
* Custom collection used by NestedTree trait.
*
* General access methods:
*
* $collection->toNested(); // Converts collection to an eager loaded one.
*
*/
class TreeCollection extends CollectionBase
{
/**
* Converts a flat collection of nested set models to an set where
* children is eager loaded
* @param bool $removeOrphans Remove nodes that exist without their parents.
* @return Illuminate\Database\Eloquent\Collection
*/
public function toNested($removeOrphans = true)
{
/*
* Set new collection for "children" relations
*/
$collection = $this->getDictionary();
foreach ($collection as $key => $model) {
$model->setRelation('children', new CollectionBase);
}
/*
* Assign all child nodes to their parents
*/
$nestedKeys = [];
foreach($collection as $key => $model) {
if (!$parentKey = $model->getParentId())
continue;
if (array_key_exists($parentKey, $collection)) {
$collection[$parentKey]->children[] = $model;
$nestedKeys[] = $model->getKey();
}
elseif ($removeOrphans) {
$nestedKeys[] = $model->getKey();
}
}
/*
* Remove processed nodes
*/
foreach ($nestedKeys as $key) {
unset($collection[$key]);
}
return new CollectionBase($collection);
}
}