dev-master
9999999-dev https://github.com/yujin1st/yii2-nested-set-behaviorThis extension allows you to get functional for nested set trees.
BSD-3-Clause
The Requires
extension nested set yii behavior
This extension allows you to get functional for nested set trees.
This extension allows you to get functional for nested set trees., (*1)
This extension supports parentId attribute updating - this is main difference from original creocoder's version, (*2)
The preferred way to install this extension is through composer., (*3)
Either run, (*4)
php composer.phar require yujin1st/yii2-nested-set-behavior "*"
or add, (*5)
"yujin1st/yii2-nested-set-behavior": "*"
to the require section of your composer.json
file., (*6)
First you need to configure model as follows:, (*7)
class Category extends ActiveRecord { public function behaviors() { return [ [ 'class' => NestedSet::className(), ], ]; } /** * @return CategoryQuery */ public static function find() { return Yii::createObject(CategoryQuery::className(), [get_called_class()]); } }
Second you need to configure query model as follows:, (*8)
class CategoryQuery extends ActiveQuery { public function behaviors() { return [ [ 'class' => NestedSetQuery::className(), ], ]; } }
There is no need to validate fields specified in leftAttribute
,
rightAttribute
, rootAttribute
and levelAttribute
options. Moreover,
there could be problems if there are validation rules for these. Please
check if there are no rules for fields mentioned in model's rules() method., (*9)
In case of storing a single tree per database, DB structure can be built with
schema/schema.sql
. If you're going to store multiple trees you'll need
schema/schema-many-roots.sql
., (*10)
By default leftAttribute
, rightAttribute
and levelAttribute
values are
matching field names in default DB schemas so you can skip configuring these., (*11)
There are two ways this behavior can work: one tree per table and multiple trees
per table. The mode is selected based on the value of hasManyRoots
option that
is false
by default meaning single tree mode. In multiple trees mode you can
set rootAttribute
option to match existing field in the table storing the tree., (*12)
You can specify parentId
attribute name - and behaviour will update this property while you insert or move the record.
This feature doesn't affect to behaviour at all (and is switched off by default),
but seems convenient way to get parent's primary key without additional queries., (*13)
In the following we'll use an example model Category
with the following in its
DB:, (*14)
- 1. Mobile phones - 2. iPhone - 3. Samsung - 4. X100 - 5. C200 - 6. Motorola - 7. Cars - 8. Audi - 9. Ford - 10. Mercedes
In this example we have two trees. Tree roots are ones with ID=1 and ID=7., (*15)
Using NestedSet::roots()
:, (*16)
$roots = Category::find()->roots()->all();
Result:, (*17)
Array of Active Record objects corresponding to Mobile phones and Cars nodes., (*18)
Using NestedSet::descendants()
:, (*19)
$category = Category::find(1); $descendants = $category->descendants()->all();
Result:, (*20)
Array of Active Record objects corresponding to iPhone, Samsung, X100, C200 and Motorola., (*21)
Using NestedSet::children()
:, (*22)
$category = Category::find(1); $descendants = $category->children()->all();
Result:, (*23)
Array of Active Record objects corresponding to iPhone, Samsung and Motorola., (*24)
Using NestedSet::ancestors()
:, (*25)
$category = Category::find(5); $ancestors = $category->ancestors()->all();
Result:, (*26)
Array of Active Record objects corresponding to Samsung and Mobile phones., (*27)
Using NestedSet::parent()
:, (*28)
$category = Category::find(9); $parent = $category->parent()->one();
Result:, (*29)
Array of Active Record objects corresponding to Cars., (*30)
Using NestedSet::prev()
or
NestedSet::next()
:, (*31)
$category = Category::find(9); $nextSibling = $category->next()->one();
Result:, (*32)
Array of Active Record objects corresponding to Mercedes., (*33)
You can get the whole tree using standard AR methods like the following., (*34)
For single tree per table:, (*35)
Category::find()->addOrderBy('lft')->all();
For multiple trees per table:, (*36)
Category::find()->where('root = ?', [$root_id])->addOrderBy('lft')->all();
In this section we'll build a tree like the one used in the previous section., (*37)
You can create a root node using NestedSet::saveNode()
.
In a single tree per table mode you can create only one root node. If you'll attempt
to create more there will be CException thrown., (*38)
$root = new Category; $root->title = 'Mobile Phones'; $root->saveNode(); $root = new Category; $root->title = 'Cars'; $root->saveNode();
Result:, (*39)
- 1. Mobile Phones - 2. Cars
There are multiple methods allowing you adding child nodes. To get more info about these refer to API. Let's use these to add nodes to the tree we have:, (*40)
$category1 = new Category; $category1->title = 'Ford'; $category2 = new Category; $category2->title = 'Mercedes'; $category3 = new Category; $category3->title = 'Audi'; $root = Category::find(1); $category1->appendTo($root); $category2->insertAfter($category1); $category3->insertBefore($category1);
Result:, (*41)
- 1. Mobile phones - 3. Audi - 4. Ford - 5. Mercedes - 2. Cars
Logically the tree above doesn't looks correct. We'll fix it later., (*42)
$category1 = new Category; $category1->title = 'Samsung'; $category2 = new Category; $category2->title = 'Motorola'; $category3 = new Category; $category3->title = 'iPhone'; $root = Category::find(2); $category1->appendTo($root); $category2->insertAfter($category1); $category3->prependTo($root);
Result:, (*43)
- 1. Mobile phones - 3. Audi - 4. Ford - 5. Mercedes - 2. Cars - 6. iPhone - 7. Samsung - 8. Motorola
$category1 = new Category; $category1->title = 'X100'; $category2 = new Category; $category2->title = 'C200'; $node = Category::find(3); $category1->appendTo($node); $category2->prependTo($node);
Result:, (*44)
- 1. Mobile phones - 3. Audi - 9. С200 - 10. X100 - 4. Ford - 5. Mercedes - 2. Cars - 6. iPhone - 7. Samsung - 8. Motorola
In this section we'll finally make our tree logical., (*45)
There are several methods allowing you to modify a tree. To get more info about these refer to API., (*46)
Let's start:, (*47)
// move phones to the proper place $x100 = Category::find(10); $c200 = Category::find(9); $samsung = Category::find(7); $x100->moveAsFirst($samsung); $c200->moveBefore($x100); // now move all Samsung phones branch $mobile_phones = Category::find(1); $samsung->moveAsFirst($mobile_phones); // move the rest of phone models $iphone = Category::find(6); $iphone->moveAsFirst($mobile_phones); $motorola = Category::find(8); $motorola->moveAfter($samsung); // move car models to appropriate place $cars = Category::find(2); $audi = Category::find(3); $ford = Category::find(4); $mercedes = Category::find(5); foreach([$audi, $ford, $mercedes] as $category) { $category->moveAsLast($cars); }
Result:, (*48)
- 1. Mobile phones - 6. iPhone - 7. Samsung - 10. X100 - 9. С200 - 8. Motorola - 2. Cars - 3. Audi - 4. Ford - 5. Mercedes
There is a special moveAsRoot()
method that allows moving a node and making it
a new root. All descendants are moved as well in this case., (*49)
Example:, (*50)
$node = Category::find(10); $node->moveAsRoot();
There are three methods to get node type: isRoot()
, isLeaf()
, isDescendantOf()
., (*51)
Example:, (*52)
$root = Category::find(1); VarDumper::dump($root->isRoot()); //true; VarDumper::dump($root->isLeaf()); //false; $node = Category::find(9); VarDumper::dump($node->isDescendantOf($root)); //true; VarDumper::dump($node->isRoot()); //false; VarDumper::dump($node->isLeaf()); //true; $samsung = Category::find(7); VarDumper::dump($node->isDescendantOf($samsung)); //true;
$categories = Category::find()->addOrderBy('lft')->all(); $level = 0; foreach ($categories as $n => $category) { if ($category->level == $level) { echo Html::endTag('li') . "\n"; } elseif ($category->level > $level) { echo Html::beginTag('ul') . "\n"; } else { echo Html::endTag('li') . "\n"; for ($i = $level - $category->level; $i; $i--) { echo Html::endTag('ul') . "\n"; echo Html::endTag('li') . "\n"; } } echo Html::beginTag('li'); echo Html::encode($category->title); $level = $category->level; } for ($i = $level; $i; $i--) { echo Html::endTag('li') . "\n"; echo Html::endTag('ul') . "\n"; }
$categories = Category::find()->andWhere('level<3')->all(); $list = []; foreach ($categories as $category) { // if record is root it may have the **null** value (for correct foreign keys) // but you can specify this in **emptyParentAttributeValue** property $list[$category->parentId ? $category->parentId : 0][] = $category; } foreach ($list[0] as $category) { echo $category->title; foreach ($list[$category->id] as $subCategory){ echo ' - ' . $subCategory->title; } }
This extension allows you to get functional for nested set trees.
BSD-3-Clause
extension nested set yii behavior