Skip to content

Instantly share code, notes, and snippets.

@ChVuagniaux
Last active July 13, 2022 13:34
Show Gist options
  • Save ChVuagniaux/ad4f9e5ddfd2009b604beda36075b2fd to your computer and use it in GitHub Desktop.
Save ChVuagniaux/ad4f9e5ddfd2009b604beda36075b2fd to your computer and use it in GitHub Desktop.
OctoberCMS model Convert SimpleTree to NestedTree https://octobercms.inetis.ch/convert-your-model-data-simpletree-nestedtree
<?php
/**
* This script convert a model using
* \October\Rain\Database\Traits\SimpleTree to
* \October\Rain\Database\Traits\NestedTree
*
* Before run create required fields in your DB for NestedTree
* ( https://octobercms.com/docs/database/traits#nested-tree )
*/
function buildNestedTree($items, $level, &$nest)
{
$items->each(function ($item) use (&$nest, $level) {
$item->nest_left = $nest++;
$item->nest_depth = $level;
// Add `->sortBy('sort_order')` if you have a custom sort column
$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())
// ->orderBy('sort_order') if you have a custom sort column
->get();
buildNestedTree($roots, $level, $nest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment