Technical notes about OctoberCMS a Laravel CMS. Notes are written by inetis team, a Swiss webagency

<- Back

Convert your model data from SimpleTree to NestedTree

Posted on by

A simple script to make your existing data compatible with NestedTree trait

Few time a project start small and grow after, this rule is also true for model tree : on the beginning a SimpleTree (parent and child) is fine. But after you need to perform action on a branch and need to convert your model from SimpleTree to a NestedTree and fill nest_left, nest_right and nest_depth columns. With the follwing code you will can do that simply.

  1. Ensure the following fields exist in your table : parent_id, nest_left, nest_right and nest_depth
    for more info read official documentation
  2. Copy code below in a custom route file or in a Console command :
/*
 * 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();
        buildTree($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);
  1. Once the process is done you can replace the SimpleTree trait by NestedTree and (if everything went well) use the power of NestedTree