Skip to content

Instantly share code, notes, and snippets.

@amdad
Forked from ChVuagniaux/convertToNestedTree.php
Last active April 21, 2019 16:23
Show Gist options
  • Save amdad/4e0b19721ffb14078a2f0c657753f029 to your computer and use it in GitHub Desktop.
Save amdad/4e0b19721ffb14078a2f0c657753f029 to your computer and use it in GitHub Desktop.
/*
* This script migrate model data from SimpleTree to NestedTree
*
* @see \October\Rain\Database\Traits\SimpleTree
* @see \October\Rain\Database\Traits\NestedTree
*
* Before executing this ensure that your model implement SimpleTree
* and switch to NestedTree only when the process is complete
*/
function buildNestedTree($items, $level, &$nest)
{
$items->each(function ($item) use (&$nest, $level) {
$item->nest_left = $nest++;
$item->nest_depth = $level;
$children = $item->getChildren();
buildNestedTree($children, $level + 1, $nest);
$item->nest_right = $nest++;
$item->save();
});
}
// Your model that implement \October\Rain\Database\Traits\SimpleTree
$model = new \VendorCode\PluginName\Models\YourModel();
$level = 0;
$nest = 1;
$roots = $model->whereNull($model->getParentColumnName())->get();
// Build the Tree from parents and goes down gradually
buildNestedTree($roots, $level, $nest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment