diff --git a/src/Models/ClosureTable.php b/src/Models/ClosureTable.php index 0f3ded3..e48d854 100644 --- a/src/Models/ClosureTable.php +++ b/src/Models/ClosureTable.php @@ -60,11 +60,11 @@ private function selectRowsToInsert($ancestorId, $descendantId) $depth = $this->getDepthColumn(); $select = " - SELECT tbl.{$ancestor} AS ancestor, ? AS descendant, tbl.{$depth}+1 AS depth + SELECT tbl.{$ancestor} AS {$ancestor}, ? AS {$descendant}, tbl.{$depth}+1 AS {$depth} FROM {$table} AS tbl WHERE tbl.{$descendant} = ? UNION ALL - SELECT ? AS ancestor, ? AS descendant, 0 AS depth + SELECT ? AS {$ancestor}, ? AS {$descendant}, 0 AS {$depth} "; $rows = $this->getConnection()->select($select, [ diff --git a/src/Models/Entity.php b/src/Models/Entity.php index 9f4435a..b5d04de 100644 --- a/src/Models/Entity.php +++ b/src/Models/Entity.php @@ -7,7 +7,6 @@ use Franzose\ClosureTable\Extensions\Collection; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; -use Illuminate\Support\Arr; use InvalidArgumentException; /** @@ -1763,7 +1762,7 @@ public static function createFromArray(array $tree, EntityInterface $parent = nu $entities = []; foreach ($tree as $item) { - $children = Arr::pull($item, static::CHILDREN_RELATION_NAME); + $children = $item[static::CHILDREN_RELATION_NAME] ?? []; /** * @var Entity $entity diff --git a/tests/Models/Entity/TreeTests.php b/tests/Models/Entity/TreeTests.php index ae09ec4..6cae625 100644 --- a/tests/Models/Entity/TreeTests.php +++ b/tests/Models/Entity/TreeTests.php @@ -2,6 +2,7 @@ namespace Franzose\ClosureTable\Tests\Models\Entity; +use Franzose\ClosureTable\Extensions\Collection; use Franzose\ClosureTable\Models\ClosureTable; use Franzose\ClosureTable\Models\Entity; use Franzose\ClosureTable\Tests\BaseTestCase; @@ -162,4 +163,47 @@ public function testCreateFromArrayBug81() static::assertEquals(0, $child2->countChildren()); static::assertEquals(19, $child2->getKey()); } + + /** + * @link https://github.com/franzose/ClosureTable/issues/239 + */ + public function testCreateFromArrayIssue239() + { + Page::createFromArray([ + [ + 'id' => 100, + 'children' => [ + ['id' => 200], + ['id' => 300], + ['id' => 400], + ['id' => 500], + [ + 'id' => 600, + 'children' => [ + ['id' => 700], + ['id' => 800], + ] + ], + ] + ] + ]); + + /** @var Page $page */ + $page = Page::find(100); + + /** @var Collection|Page[] $children */ + $children = $page->getChildren(); + + static::assertCount(5, $children); + static::assertEquals(200, $children->get(0)->id); + static::assertEquals(300, $children->get(1)->id); + static::assertEquals(400, $children->get(2)->id); + static::assertEquals(500, $children->get(3)->id); + static::assertEquals(600, $children->get(4)->id); + + $childrenOf600 = $children->get(4)->getChildren(); + static::assertCount(2, $childrenOf600); + static::assertEquals(700, $childrenOf600->get(0)->id); + static::assertEquals(800, $childrenOf600->get(1)->id); + } }