PHP code example of matperez / yii2-materialized-path
1. Go to this page and download the library: Download matperez/yii2-materialized-path 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/ */
matperez / yii2-materialized-path example snippets
$this->createTable('tree', [
'id' => Schema::TYPE_PK,
'name' => Schema::TYPE_STRING.' NOT NULL',
'path' => Schema::TYPE_STRING.' NOT NULL DEFAULT \'.\'',
'position' => Schema::TYPE_INTEGER.' NOT NULL DEFAULT 0',
'level' => Schema::TYPE_INTEGER.' NOT NULL DEFAULT 0',
]);
use matperez\mp\MaterializedPathBehavior;
use matperez\mp\MaterializedPathQuery;
class Tree extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => MaterializedPathBehavior::className(),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['position', 'level'], 'integer'],
[['path'], 'string', 'max' => 255]
];
}
/**
* Query factory
* @return MaterializedPathQuery
*/
public static function find()
{
return new MaterializedPathQuery(get_called_class());
}
}
$root = new Tree(['name' => 'root']);
$root->makeRoot();
$child = new Tree(['name' => 'child']);
$child->appendTo($root);
$node = Tree::findOne(['name' => 'child']);
// move node up
$node->setPosition($node->position - 1);
// move node down
$node->setPosition($node->position + 1);
$roots = Tree::find()->roots()->all();
$root = Tree::find()->roots()->one();
foreach($root->children as $child) {
foreach($child->children as $subchild) {
// do the things with a subchild
}
}