protected function mapTreeRecursive(array $tree, $parentKey = null, &$affectedKeys = [])
{
// For every attribute entry: We'll need to instantiate a new node either
// from the database (if the primary key was supplied) or a new instance. Then,
// append all the remaining data attributes (including the `parent_id` if
// present) and save it. Finally, tail-recurse performing the same
// operations for any child node present. Setting the `parent_id` property at
// each level will take care of the nesting work for us.
foreach ($tree as $attributes) {
$node = $this->firstOrNew($this->getSearchAttributes($attributes));
$data = $this->getDataAttributes($attributes);
if (!is_null($parentKey)) {
$data[$node->getParentColumnName()] = $parentKey;
}
$node->fill($data);
$result = $node->save();
if (!$result) {
return false;
}
if (!$node->isRoot()) {
$node->makeLastChildOf($node->parent);
}
$affectedKeys[] = $node->getKey();
if (array_key_exists($this->getChildrenKeyName(), $attributes)) {
$children = $attributes[$this->getChildrenKeyName()];
if (count($children) > 0) {
$result = $this->mapTreeRecursive($children, $node->getKey(), $affectedKeys);
if (!$result) {
return false;
}
}
}
}
return true;
}