首页
/ Nested Set 行为扩展技术文档

Nested Set 行为扩展技术文档

2024-12-25 19:24:28作者:范靓好Udolf

1. 安装指南

要使用 Yii 2 的 Nested Set 行为扩展,首先需要配置模型。你需要在模型的 behaviors() 方法中添加相应的行为配置。

public function behaviors()
{
    return array(
        'nestedSetBehavior' => array(
            'class' => 'ext.yiiext.behaviors.model.trees.NestedSetBehavior',
            'leftAttribute' => 'lft',
            'rightAttribute' => 'rgt',
            'levelAttribute' => 'level',
        ),
    );
}

确保没有对这些属性(leftAttribute, rightAttribute, rootAttributelevelAttribute)进行验证。如果存在验证规则,可能会出现问题。

2. 项目的使用说明

Nested Set 行为扩展允许将树结构存储在数据库中。以下是如何使用该扩展的示例:

获取所有根节点

$roots = Category::model()->roots()->findAll();

获取一个节点的所有后代

$category = Category::model()->findByPk(1);
$descendants = $category->descendants()->findAll();

获取一个节点的所有子节点

$category = Category::model()->findByPk(1);
$children = $category->children()->findAll();

获取一个节点的所有祖先

$category = Category::model()->findByPk(5);
$ancestors = $category->ancestors()->findAll();

获取一个节点的父节点

$category = Category::model()->findByPk(9);
$parent = $category->parent()->find();

获取一个节点的兄弟节点

$category = Category::model()->findByPk(9);
$nextSibling = $category->next()->find();

获取整个树

对于单树结构,可以使用:

Category::model()->findAll(array('order' => 'lft'));

对于多树结构,可以使用:

Category::model()->findAll(array('condition' => 'root=?', 'order' => 'lft'), array($root_id));

3. 项目API使用文档

关于具体的 API 使用,请参考项目在 GitHub 上的 Wiki 文档。

4. 项目安装方式

创建根节点

$root = new Category;
$root->title = 'Mobile Phones';
$root->saveNode();

添加子节点

$category1 = new Category;
$category1->title = 'Ford';
$category1->appendTo($root);

修改树结构

$x100 = Category::model()->findByPk(10);
$x100->moveAsFirst($samsung);

移动节点成为新的根节点

$node = Category::model()->findByPk(10);
$node->moveAsRoot();

节点类型识别

$root = Category::model()->findByPk(1);
CVarDumper::dump($root->isRoot()); // true;
CVarDumper::dump($root->isLeaf()); // false;

以上是 Nested Set 行为扩展的基本用法和技术文档概览。更多详细信息,请参考官方文档和 GitHub 上的项目 Wiki。

登录后查看全文
热门项目推荐