diff --git a/src/Extensions/Collection.php b/src/Extensions/Collection.php index e3cd8f7..66adff1 100644 --- a/src/Extensions/Collection.php +++ b/src/Extensions/Collection.php @@ -171,7 +171,7 @@ protected function makeTree(array $items) $parentId = $item->parent_id; if (array_key_exists($parentId, $result)) { - $result[$parentId]->children->add($item); + $result[$parentId]->appendChild($item); } else { $tops[] = $item; } diff --git a/src/Models/Entity.php b/src/Models/Entity.php index e73b0ae..df423c6 100644 --- a/src/Models/Entity.php +++ b/src/Models/Entity.php @@ -64,6 +64,8 @@ */ class Entity extends Eloquent implements EntityInterface { + const CHILDREN_RELATION_NAME = 'children'; + /** * ClosureTable model instance. * @@ -263,7 +265,7 @@ public function getRealDepthColumn() */ public function getChildrenRelationIndex() { - return 'children'; + return static::CHILDREN_RELATION_NAME; } /** @@ -927,6 +929,29 @@ public function addChildren(array $children, $from = null) return $this; } + /** + * Appends the given entity to the children relation. + * + * @param Entity $entity + * @internal + */ + public function appendChild(Entity $entity) + { + $this->getChildrenRelation()->add($entity); + } + + /** + * @return Collection + */ + private function getChildrenRelation() + { + if (!$this->relationLoaded(static::CHILDREN_RELATION_NAME)) { + $this->setRelation(static::CHILDREN_RELATION_NAME, new Collection()); + } + + return $this->getRelation(static::CHILDREN_RELATION_NAME); + } + /** * Removes a model's child with given position. * @@ -1665,7 +1690,7 @@ public static function getTree(array $columns = ['*']) $instance = new static; return $instance - ->load('children') + ->load(static::CHILDREN_RELATION_NAME) ->orderBy($instance->getParentIdColumn()) ->orderBy($instance->getPositionColumn()) ->get($instance->prepareTreeQueryColumns($columns)) @@ -1727,7 +1752,7 @@ public static function createFromArray(array $tree, EntityInterface $parent = nu $entities = []; foreach ($tree as $item) { - $children = Arr::pull($item, 'children'); + $children = Arr::pull($item, static::CHILDREN_RELATION_NAME); /** * @var Entity $entity diff --git a/tests/Extensions/CollectionTests.php b/tests/Extensions/CollectionTests.php index 31c49cb..0d3ded5 100644 --- a/tests/Extensions/CollectionTests.php +++ b/tests/Extensions/CollectionTests.php @@ -1,6 +1,7 @@ 1]); $child = new Page(['id' => 2, 'parent_id' => 1]); $grandChild = new Page(['id' => 3, 'parent_id' => 2]); $tree = (new Collection([$root, $child, $grandChild]))->toTree(); + static::assertEquals(0, $queries); static::assertCount(1, $tree); $children = $tree->get(0)->children;