Conditions | 4 |
Paths | 5 |
Total Lines | 32 |
Code Lines | 17 |
Lines | 0 |
Ratio | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
21 | public function toTree(string $childrenRelation = 'children'): static |
||
22 | { |
||
23 | if ($this->isEmpty()) { |
||
24 | return $this; |
||
25 | } |
||
26 | |||
27 | $model = $this->first(); |
||
28 | |||
29 | $parentKeyName = $model->relationLoaded('pivot') |
||
30 | ? 'pivot.' . $model->getParentKeyName() |
||
31 | : 'pivot_' . $model->getParentKeyName(); |
||
32 | |||
33 | $localKeyName = $model->getLocalKeyName(); |
||
34 | |||
35 | $depthName = $model->getDepthName(); |
||
36 | |||
37 | $depths = $this->pluck($depthName); |
||
38 | |||
39 | $graph = new static( |
||
40 | $this->where($depthName, $depths->min())->values() |
||
41 | ); |
||
42 | |||
43 | $itemsByParentKey = $this->groupBy($parentKeyName); |
||
44 | |||
45 | foreach ($this->items as $item) { |
||
46 | $item->setRelation( |
||
47 | $childrenRelation, |
||
48 | $itemsByParentKey[$item->$localKeyName] ?? new static() |
||
49 | ); |
||
50 | } |
||
51 | |||
52 | return $graph; |
||
53 | } |
||
55 |