NestedSetsBehavior
API reference › Nested sets behavior › NestedSetsBehavior
Manages hierarchical data in ActiveRecord models using the nested sets pattern.
Maintains the left, right and depth attributes of each node and, when $treeAttribute is set, a tree identifier
that stores several trees in one table. Structural writes serialize on a per-table writer lock held until the
outermost transaction ends, so the connection must enable savepoints and the nested_sets_lock registry table must
exist. A plain delete() acquires that lock in beforeDelete() and therefore requires an active Yii
transaction, for example through ActiveRecord::transactions().
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$depth | int | NestedSetsBehavior | |
$depthAttribute | "depth" | Attribute name. Default: 'depth'. | NestedSetsBehavior |
$leftAttribute | "lft" | Attribute name. Default: 'lft'. | NestedSetsBehavior |
$lft | int | NestedSetsBehavior | |
$lockTimeout | int | Maximum wait in seconds for each guard-row acquisition; valid range is 1 through 3600. Default: 10. | NestedSetsBehavior |
$owner | yii\ | The owner of this behavior Default: null. | yii\ |
$rgt | int | NestedSetsBehavior | |
$rightAttribute | "rgt" | Attribute name. Default: 'rgt'. | NestedSetsBehavior |
$treeAttribute | string| | Name of the attribute that stores the tree identifier, or false to keep a single tree per table. Default: false. | NestedSetsBehavior |
$depthValue protected | int| | Cached depth of the owner, or null when it must be read from the owner attributes. Default: null. | NestedSetsBehavior |
$leftValue protected | int| | Cached left value of the owner, or null when it must be read from the owner attributes. Default: null. | NestedSetsBehavior |
$node protected | yii\<yii2\ | Target node of the pending operation, or null when the operation has no target. Default: null. | NestedSetsBehavior |
$operation protected | string| | Pending operation, one of the OPERATION_* constants, or null when no structural operation is pending. Default: null. | NestedSetsBehavior |
$rightValue protected | int| | Cached right value of the owner, or null when it must be read from the owner attributes. Default: null. | NestedSetsBehavior |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__get() | Returns the value of an object property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets value of an object property. | yii\ |
__unset() | Sets an object property to null. | yii\ |
acquireTreeLock() | Acquires the table writer lock before application reads or raw SQL in an existing Yii transaction. | NestedSetsBehavior |
afterDelete() | Closes the gap left by the deleted owner, moving the children of a node deleted on its own one level up. | NestedSetsBehavior |
afterInsert() | Assigns the primary key of a new root as its tree identifier when $treeAttribute is enabled. | NestedSetsBehavior |
afterRefresh() | Clears cached coordinates after a model refresh without cancelling an active operation. | NestedSetsBehavior |
afterUpdate() | Moves the owner subtree to the position requested by the pending operation and reloads the owner coordinates. | NestedSetsBehavior |
appendTo() | Appends the owner as the last child of the target node, inserting a new owner or moving an existing subtree. | NestedSetsBehavior |
attach() | Attaches the behavior object to the component. | yii\ |
beforeDelete() | Acquires the table writer lock, reloads the owner coordinates, and rejects deleting a root node on its own. | NestedSetsBehavior |
beforeInsert() | Reloads the target coordinates and assigns the coordinates of the new owner according to the pending operation. | NestedSetsBehavior |
beforeUpdate() | Reloads the coordinates of the owner and the target and validates the pending move before the owner is updated. | NestedSetsBehavior |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
children() | Returns a query for the descendants of the owner, ordered by left value and optionally limited in depth. | NestedSetsBehavior |
className() static | Returns the fully qualified name of this class. | yii\ |
deleteWithChildren() | Deletes the owner together with all its descendants. | NestedSetsBehavior |
detach() | Detaches the behavior object from the component. | yii\ |
events() | Returns the ActiveRecord lifecycle event handlers of the behavior. | NestedSetsBehavior |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined. | yii\ |
init() | Initializes the object. | yii\ |
insertAfter() | Places the owner as the next sibling of the target node, inserting a new owner or moving an existing subtree. | NestedSetsBehavior |
insertBefore() | Places the owner as the previous sibling of the target node, inserting a new owner or moving an existing subtree. | NestedSetsBehavior |
invalidateCache() | Clears the cached coordinates and discards the pending operation and target node. | NestedSetsBehavior |
isChildOf() | Returns whether the owner is a descendant of the given node within the same tree. | NestedSetsBehavior |
isLeaf() | Returns whether the owner has no descendants. | NestedSetsBehavior |
isRoot() | Returns whether the owner is a root node. | NestedSetsBehavior |
leaves() | Returns a query for the leaf descendants of the owner, ordered by left value. | NestedSetsBehavior |
makeRoot() | Makes the owner a root, starting a new tree for a new owner or promoting an existing subtree to a new tree. | NestedSetsBehavior |
next() | Returns a query for the next sibling of the owner. | NestedSetsBehavior |
parents() | Returns a query for the ancestors of the owner, ordered by left value and optionally limited in depth. | NestedSetsBehavior |
prependTo() | Prepends the owner as the first child of the target node, inserting a new owner or moving an existing subtree. | NestedSetsBehavior |
prev() | Returns a query for the previous sibling of the owner. | NestedSetsBehavior |
beforeInsertNode() protected | Assigns the coordinates of a new child or sibling at the given position and opens space for it in the tree. | NestedSetsBehavior |
beforeInsertRootNode() protected | Assigns root coordinates to a new owner. | NestedSetsBehavior |
moveNode() protected | Moves the owner subtree to the position described by the context, within its tree or into another tree. | NestedSetsBehavior |
moveNodeAsRoot() protected | Promotes the owner subtree to a new tree identified by the owner primary key and closes the gap it leaves. | NestedSetsBehavior |
shiftLeftRightAttribute() protected | Adds the delta to every left and right value greater than or equal to the given value within the owner tree. | NestedSetsBehavior |
Constants
Section titled “Constants”| Constant | Value | Description | Defined by |
|---|---|---|---|
OPERATION_APPEND_TO | 'appendTo' | Identifies the operation that places the owner as the last child of a target node. | NestedSetsBehavior |
OPERATION_DELETE_WITH_CHILDREN | 'deleteWithChildren' | Identifies the operation that deletes the owner together with all its descendants. | NestedSetsBehavior |
OPERATION_INSERT_AFTER | 'insertAfter' | Identifies the operation that places the owner as the next sibling of a target node. | NestedSetsBehavior |
OPERATION_INSERT_BEFORE | 'insertBefore' | Identifies the operation that places the owner as the previous sibling of a target node. | NestedSetsBehavior |
OPERATION_MAKE_ROOT | 'makeRoot' | Identifies the operation that creates the owner as a root or promotes it to the root of a new tree. | NestedSetsBehavior |
OPERATION_PREPEND_TO | 'prependTo' | Identifies the operation that places the owner as the first child of a target node. | NestedSetsBehavior |
Method details
Section titled “Method details”acquireTreeLock()
Section titled “acquireTreeLock() ”public function acquireTreeLock(): voidAcquires the table writer lock before application reads or raw SQL in an existing Yii transaction.
The database retains the lock until that transaction commits or rolls back.
Throws
Throwable: if no Yii transaction is active, savepoints are disabled,$lockTimeoutis out of range, thenested_sets_lockregistry is missing, or the lock wait times out.
afterDelete()
Section titled “afterDelete() ”public function afterDelete(): voidCloses the gap left by the deleted owner, moving the children of a node deleted on its own one level up.
Throws
yii\db\Exception: if updating the remaining coordinates fails.
afterInsert()
Section titled “afterInsert() ”public function afterInsert(): voidAssigns the primary key of a new root as its tree identifier when $treeAttribute is enabled.
Throws
yii\db\Exception: if the owner model has no primary key or the tree identifier update fails.
afterRefresh()
Section titled “afterRefresh() ”public function afterRefresh(): voidClears cached coordinates after a model refresh without cancelling an active operation.
afterUpdate()
Section titled “afterUpdate() ”public function afterUpdate(): voidMoves the owner subtree to the position requested by the pending operation and reloads the owner coordinates.
Throws
RuntimeException: if the pending operation does not move the owner relative to a target node.yii\db\StaleObjectException: if the owner no longer exists when its coordinates are reloaded.
appendTo()
Section titled “appendTo() ”public function appendTo(yii2\extensions\nestedsets\T $node, bool $runValidation = true, list<string>|null $attributes = null): boolAppends the owner as the last child of the target node, inserting a new owner or moving an existing subtree.
Runs in its own transaction, acquires the table writer lock, rolls back and restores the owner on failure, and reloads the coordinates of the owner and the target on success.
Parameters
| Parameter | Type | Description |
|---|---|---|
$node | yii2\ | Node that becomes the parent of the owner. |
$runValidation | bool | Whether to validate the owner before saving. |
$attributes | list<string>| | Attributes to save, or null to save all attributes. |
Returns
bool: Whether the owner was saved.
Throws
Throwable: if a lifecycle handler or database operation fails.
beforeDelete()
Section titled “beforeDelete() ”public function beforeDelete(): voidAcquires the table writer lock, reloads the owner coordinates, and rejects deleting a root node on its own.
Throws
yii\db\Exception: if the owner is a new record.yii\base\NotSupportedException: if the owner is a root and the deletion is not run bydeleteWithChildren().yii\db\StaleObjectException: if the owner no longer exists or its optimistic lock version has changed.Throwable: if the writer lock cannot be acquired, for example without an active Yii transaction.
beforeInsert()
Section titled “beforeInsert() ”public function beforeInsert(): voidReloads the target coordinates and assigns the coordinates of the new owner according to the pending operation.
Throws
yii\db\Exception: if the target node is a new record or uses another connection or table, if a sibling of a root is requested, or if a second root is created while$treeAttributeisfalse.yii\base\NotSupportedException: if no supported operation is pending, for example on a plaininsert().yii\db\StaleObjectException: if the target node no longer exists.
beforeUpdate()
Section titled “beforeUpdate() ”public function beforeUpdate(): voidReloads the coordinates of the owner and the target and validates the pending move before the owner is updated.
For structural moves, also marks the optimistic lock attribute dirty so that the update checks and increments it.
Throws
yii\db\Exception: if the move is invalid: promoting a root, making a root while$treeAttributeisfalse, or targeting a new record, the owner itself, one of its descendants, or a root for sibling moves.yii\db\StaleObjectException: if the owner or the target no longer exists, or the owner optimistic lock version has changed.
children()
Section titled “children() ”public function children(int|null $depth = null): yii\db\ActiveQuery<yii2\extensions\nestedsets\T>Returns a query for the descendants of the owner, ordered by left value and optionally limited in depth.
Parameters
| Parameter | Type | Description |
|---|---|---|
$depth | int| | Maximum number of levels below the owner, or null for all descendants. |
Returns
yii\db\ActiveQuery<yii2\extensions\nestedsets\T>: Query for the descendants of the owner.
deleteWithChildren()
Section titled “deleteWithChildren() ”public function deleteWithChildren(): bool|intDeletes the owner together with all its descendants.
Runs in its own transaction regardless of the model transactions() configuration, acquires the table writer
lock, reloads the owner coordinates before deleting, and rolls back and restores the owner on failure.
Returns
bool|int: Number of deleted rows, or false if ActiveRecord::beforeDelete() cancels the deletion.
Throws
Throwable: if a lifecycle handler or database operation fails.
events()
Section titled “events() ”public function events(): string[]Returns the ActiveRecord lifecycle event handlers of the behavior.
Returns
string[]: The event handlers of the behavior.
insertAfter()
Section titled “insertAfter() ”public function insertAfter(yii\db\ActiveRecord $node, bool $runValidation = true, list<string>|null $attributes = null): boolPlaces the owner as the next sibling of the target node, inserting a new owner or moving an existing subtree.
Runs in its own transaction, acquires the table writer lock, rolls back and restores the owner on failure, and reloads the coordinates of the owner and the target on success.
Parameters
| Parameter | Type | Description |
|---|---|---|
$node | yii\ | Node that becomes the previous sibling of the owner. |
$runValidation | bool | Whether to validate the owner before saving. |
$attributes | list<string>| | Attributes to save, or null to save all attributes. |
Returns
bool: Whether the owner was saved.
Throws
Throwable: if a lifecycle handler or database operation fails.
insertBefore()
Section titled “insertBefore() ”public function insertBefore(yii\db\ActiveRecord $node, bool $runValidation = true, list<string>|null $attributes = null): boolPlaces the owner as the previous sibling of the target node, inserting a new owner or moving an existing subtree.
Runs in its own transaction, acquires the table writer lock, rolls back and restores the owner on failure, and reloads the coordinates of the owner and the target on success.
Parameters
| Parameter | Type | Description |
|---|---|---|
$node | yii\ | Node that becomes the next sibling of the owner. |
$runValidation | bool | Whether to validate the owner before saving. |
$attributes | list<string>| | Attributes to save, or null to save all attributes. |
Returns
bool: Whether the owner was saved.
Throws
Throwable: if a lifecycle handler or database operation fails.
invalidateCache()
Section titled “invalidateCache() ”public function invalidateCache(): voidClears the cached coordinates and discards the pending operation and target node.
isChildOf()
Section titled “isChildOf() ”public function isChildOf(yii\db\ActiveRecord $node): boolReturns whether the owner is a descendant of the given node within the same tree.
Parameters
| Parameter | Type | Description |
|---|---|---|
$node | yii\ | Candidate ancestor of the owner. |
Returns
bool: Whether the owner lies strictly inside the boundaries of the node and shares its tree identifier.
isLeaf()
Section titled “isLeaf() ”public function isLeaf(): boolReturns whether the owner has no descendants.
Returns
bool: Whether the right value of the owner exceeds its left value by exactly 1.
isRoot()
Section titled “isRoot() ”public function isRoot(): boolReturns whether the owner is a root node.
Returns
bool: Whether the left value of the owner is 1.
leaves()
Section titled “leaves() ”public function leaves(): yii\db\ActiveQuery<yii2\extensions\nestedsets\T>Returns a query for the leaf descendants of the owner, ordered by left value.
Returns
yii\db\ActiveQuery<yii2\extensions\nestedsets\T>: Query for the descendants of the owner that have no children.
makeRoot()
Section titled “makeRoot() ”public function makeRoot(bool $runValidation = true, list<string>|null $attributes = null): boolMakes the owner a root, starting a new tree for a new owner or promoting an existing subtree to a new tree.
Runs in its own transaction, acquires the table writer lock, rolls back and restores the owner on failure, and
reloads the owner coordinates on success. Promoting an existing node requires $treeAttribute.
Parameters
| Parameter | Type | Description |
|---|---|---|
$runValidation | bool | Whether to validate the owner before saving. |
$attributes | list<string>| | Attributes to save, or null to save all attributes. |
Returns
bool: Whether the owner was saved.
Throws
Throwable: if a lifecycle handler or database operation fails.
next()
Section titled “next() ”public function next(): yii\db\ActiveQuery<yii2\extensions\nestedsets\T>Returns a query for the next sibling of the owner.
Returns
yii\db\ActiveQuery<yii2\extensions\nestedsets\T>: Query for the node whose left value follows the right value of the owner; empty when there is none.
parents()
Section titled “parents() ”public function parents(int|null $depth = null): yii\db\ActiveQuery<yii2\extensions\nestedsets\T>Returns a query for the ancestors of the owner, ordered by left value and optionally limited in depth.
Parameters
| Parameter | Type | Description |
|---|---|---|
$depth | int| | Maximum number of levels above the owner, or null for all ancestors. |
Returns
yii\db\ActiveQuery<yii2\extensions\nestedsets\T>: Query for the ancestors of the owner.
prependTo()
Section titled “prependTo() ”public function prependTo(yii\db\ActiveRecord $node, bool $runValidation = true, list<string>|null $attributes = null): boolPrepends the owner as the first child of the target node, inserting a new owner or moving an existing subtree.
Runs in its own transaction, acquires the table writer lock, rolls back and restores the owner on failure, and reloads the coordinates of the owner and the target on success.
Parameters
| Parameter | Type | Description |
|---|---|---|
$node | yii\ | Node that becomes the parent of the owner. |
$runValidation | bool | Whether to validate the owner before saving. |
$attributes | list<string>| | Attributes to save, or null to save all attributes. |
Returns
bool: Whether the owner was saved.
Throws
Throwable: if a lifecycle handler or database operation fails.
prev()
Section titled “prev() ”public function prev(): yii\db\ActiveQuery<yii2\extensions\nestedsets\T>Returns a query for the previous sibling of the owner.
Returns
yii\db\ActiveQuery<yii2\extensions\nestedsets\T>: Query for the node whose right value precedes the left value of the owner; empty when there is none.
beforeInsertNode()
Section titled “beforeInsertNode() ”protected function beforeInsertNode(int $value, int $depth): voidAssigns the coordinates of a new child or sibling at the given position and opens space for it in the tree.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int | Left value of the new node. |
$depth | int | Depth offset relative to the target node: 0 for a sibling, 1 for a child. |
Throws
yii\db\Exception: if a sibling of a root node is requested.
beforeInsertRootNode()
Section titled “beforeInsertRootNode() ”protected function beforeInsertRootNode(): voidAssigns root coordinates to a new owner.
Throws
yii\db\Exception: if$treeAttributeisfalseand the table already contains a node.
moveNode()
Section titled “moveNode() ”protected function moveNode(yii2\extensions\nestedsets\NodeContext $context): voidMoves the owner subtree to the position described by the context, within its tree or into another tree.
Parameters
| Parameter | Type | Description |
|---|---|---|
$context | NodeContext | Target position and depth offset of the move. |
moveNodeAsRoot()
Section titled “moveNodeAsRoot() ”protected function moveNodeAsRoot(mixed $treeValue): voidPromotes the owner subtree to a new tree identified by the owner primary key and closes the gap it leaves.
Parameters
| Parameter | Type | Description |
|---|---|---|
$treeValue | mixed | Identifier of the tree that currently contains the subtree. |
shiftLeftRightAttribute()
Section titled “shiftLeftRightAttribute() ”protected function shiftLeftRightAttribute(int $value, int $delta): voidAdds the delta to every left and right value greater than or equal to the given value within the owner tree.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | int | Lowest boundary value to shift, inclusive. |
$delta | int | Signed offset to add; a negative value closes a gap. |