PHP code example of creocoder / yii2-nested-sets

1. Go to this page and download the library: Download creocoder/yii2-nested-sets library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

creocoder / yii2-nested-sets example snippets


$this->createTable('{{%menu}}', [
    'id' => $this->primaryKey(),
    //'tree' => $this->integer()->notNull(),
    'lft' => $this->integer()->notNull(),
    'rgt' => $this->integer()->notNull(),
    'depth' => $this->integer()->notNull(),
    'name' => $this->string()->notNull(),
]);

use creocoder\nestedsets\NestedSetsBehavior;

class Menu extends \yii\db\ActiveRecord
{
    public function behaviors() {
        return [
            'tree' => [
                'class' => NestedSetsBehavior::className(),
                // 'treeAttribute' => 'tree',
                // 'leftAttribute' => 'lft',
                // 'rightAttribute' => 'rgt',
                // 'depthAttribute' => 'depth',
            ],
        ];
    }

    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_ALL,
        ];
    }

    public static function find()
    {
        return new MenuQuery(get_called_class());
    }
}

use creocoder\nestedsets\NestedSetsQueryBehavior;

class MenuQuery extends \yii\db\ActiveQuery
{
    public function behaviors() {
        return [
            NestedSetsQueryBehavior::className(),
        ];
    }
}

$countries = new Menu(['name' => 'Countries']);
$countries->makeRoot();

$russia = new Menu(['name' => 'Russia']);
$russia->prependTo($countries);

$australia = new Menu(['name' => 'Australia']);
$australia->appendTo($countries);

$newZeeland = new Menu(['name' => 'New Zeeland']);
$newZeeland->insertBefore($australia);

$unitedStates = new Menu(['name' => 'United States']);
$unitedStates->insertAfter($australia);

$roots = Menu::find()->roots()->all();

$leaves = Menu::find()->leaves()->all();

$countries = Menu::findOne(['name' => 'Countries']);
$leaves = $countries->leaves()->all();

$countries = Menu::findOne(['name' => 'Countries']);
$children = $countries->children()->all();

$countries = Menu::findOne(['name' => 'Countries']);
$children = $countries->children(1)->all();

$countries = Menu::findOne(['name' => 'Countries']);
$parents = $countries->parents()->all();

$countries = Menu::findOne(['name' => 'Countries']);
$parent = $countries->parents(1)->one();