matperez / yii2-materialized-path
为 Yii 框架提供的材料化路径行为
1.0.2
2016-01-13 15:50 UTC
Requires
- yiisoft/yii2: ~2.0
Requires (Dev)
- codeception/codeception: ~2.1
- codeception/specify: ~0.4
- codeception/verify: ~0.2
- yiisoft/yii2-codeception: ~2.0
This package is not auto-updated.
Last update: 2024-09-24 03:28:38 UTC
README
为 Yii2 ActiveRecord 提供的材料化路径树特性。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令:
$ composer require matperez/yii2-materialized-path
或者将以下内容添加到您的 composer.json
文件的 require
部分:
"matperez/yii2-materialized-path": "*"
迁移
运行以下命令:
$ yii migrate/create create_tree_table
打开 /path/to/migrations/m_xxxxxx_xxxxxx_create_tree_table.php
文件,在 up()
方法中添加以下内容:
$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();
树将看起来像这样:
- root
将节点追加为另一个节点的子节点
要将节点作为另一个节点的第一个子节点添加:
$child = new Tree(['name' => 'child']); $child->appendTo($root);
树将看起来像这样:
- root
- child
在兄弟节点之间上下移动节点
$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 } }
获取节点的父节点
要获取节点的所有父节点:
$node = Tree::findOne(['name' => 'child']); $parents = Tree::find()->andWhere(['id' => $node->parentIds])->all();
要获取节点的第一个父节点:
$node = Tree::findOne(['name' => 'child']); $parent = $node->parent();
删除带有子节点的节点
要删除带有子节点的节点:
$node->delete();
测试
./vendor/bin/codeception build
./vendor/bin/codeception run unit
待办事项
更多测试,更多示例