jails / li3_tree
为Lithium PHP框架提供模型树行为
dev-master
2013-06-21 22:24 UTC
Requires
- php: >=5.4
- composer/installers: dev-master
- jails/li3_behaviors: dev-master
This package is auto-updated.
Last update: 2024-08-29 04:19:49 UTC
README
需求
- PHP 5.4
- 此插件需要li3_behaviors。
- 此插件需要li3_fixtures(仅当您打算运行测试时)。
安装
将代码检出至您的库目录之一
cd libraries
git clone git@github.com:jails/li3_tree
将库包含在您的/app/config/bootstrap/libraries.php
中
Libraries::add('li3_tree');
展示
此行为使用MPTT逻辑在数据库表中存储层次数据。
约束
要使用树行为,您的表需要以下3个额外字段
- 配置字段
'parent'
。默认情况下,字段必须命名为表中的parent_id
。 - 配置字段
'left'
。默认情况下,字段必须命名为表中的lft
。 - 配置字段
'right'
。默认情况下,字段必须命名为表中的rght
。
API
将树行为附加到模型的示例
<?php //app/models/Comments.php namespace app\models; use li3_behaviors\data\model\Behaviors; class Comments extends \lithium\data\Model { use Behaviors; public $belongsTo = ['Posts']; protected $_actsAs = ['Tree' => ['scope' => ['post_id']]]; } ?>
选项
为了在同一个表中存储多个树,您需要设置'scope'
选项。例如,如果Post
有Comment
的hasMany关系,而Comment
属于Post
。为了允许在同一个表中存储多个Comment
树,您必须通过外键post_id
对Comment
进行范围限制。这样所有的Comment
树都将独立。
'scope'
可以是完整的条件
protected $_actsAs = ['Tree' => ['scope' => ['region' => 'head']]];
或者是一个简单的字段名,如外键
protected $_actsAs = ['Tree' => ['scope' => ['post_id']]];
在这种情况下,完整的条件将根据实体数据填充。这意味着如果您不包含执行良好范围CRUD操作所需的所有必要数据,则无法执行任何CRUD操作。
使用示例
<?php $root1 = Comment::create(['post_id' => 1]); $root1->save(); $root2 = Comment::create(['post_id' => 2]); $root2->save(); $neighbor1 = Comment::create(['post_id' => 1]); $neighbor1->save(); $neighbor1->moveDown(); $root1->moveUp(); $neighbor1->move(0); $subelement1 = Comment::create(['post_id' => 1, 'parent_id' => $neighbor1->id]); $subelement1->save(); var_export($root1->childrens()); var_export($subelement1->path()); ?>
问候
li3团队,Vogan以及所有使这一切成为可能的人(我的意思是,只有因为Chuck Norris同意)。