Skip to content
PHP Ecosystem
Explore

NestedSetsBehavior

API reference › Nested sets behavior › NestedSetsBehavior

classyii2\extensions\nestedsets\NestedSetsBehavior
Extendsyii\base\Behavior » yii\base\BaseObject
Implementsyii\base\Configurable
Sourcesrc/NestedSetsBehavior.php

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().

PropertyTypeDescriptionDefined by
$depthintNestedSetsBehavior
$depthAttribute"depth"Attribute name. Default: 'depth'.NestedSetsBehavior
$leftAttribute"lft"Attribute name. Default: 'lft'.NestedSetsBehavior
$lftintNestedSetsBehavior
$lockTimeoutintMaximum wait in seconds for each guard-row acquisition; valid range is 1 through 3600. Default: 10.NestedSetsBehavior
$owneryii\base\T|nullThe owner of this behavior Default: null.yii\base\Behavior
$rgtintNestedSetsBehavior
$rightAttribute"rgt"Attribute name. Default: 'rgt'.NestedSetsBehavior
$treeAttributestring|falseName of the attribute that stores the tree identifier, or false to keep a single tree per table. Default: false.NestedSetsBehavior
$depthValue protectedint|nullCached depth of the owner, or null when it must be read from the owner attributes. Default: null.NestedSetsBehavior
$leftValue protectedint|nullCached left value of the owner, or null when it must be read from the owner attributes. Default: null.NestedSetsBehavior
$node protectedyii\db\ActiveRecord<yii2\extensions\nestedsets\T>|nullTarget node of the pending operation, or null when the operation has no target. Default: null.NestedSetsBehavior
$operation protectedstring|nullPending operation, one of the OPERATION_* constants, or null when no structural operation is pending. Default: null.NestedSetsBehavior
$rightValue protectedint|nullCached right value of the owner, or null when it must be read from the owner attributes. Default: null.NestedSetsBehavior
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\BaseObject
__get()Returns the value of an object property.yii\base\BaseObject
__isset()Checks if a property is set, i.e. defined and not null.yii\base\BaseObject
__set()Sets value of an object property.yii\base\BaseObject
__unset()Sets an object property to null.yii\base\BaseObject
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\base\Behavior
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\base\BaseObject
canSetProperty()Returns a value indicating whether a property can be set.yii\base\BaseObject
children()Returns a query for the descendants of the owner, ordered by left value and optionally limited in depth.NestedSetsBehavior
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
deleteWithChildren()Deletes the owner together with all its descendants.NestedSetsBehavior
detach()Detaches the behavior object from the component.yii\base\Behavior
events()Returns the ActiveRecord lifecycle event handlers of the behavior.NestedSetsBehavior
hasMethod()Returns a value indicating whether a method is defined.yii\base\BaseObject
hasProperty()Returns a value indicating whether a property is defined.yii\base\BaseObject
init()Initializes the object.yii\base\BaseObject
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() protectedAssigns the coordinates of a new child or sibling at the given position and opens space for it in the tree.NestedSetsBehavior
beforeInsertRootNode() protectedAssigns root coordinates to a new owner.NestedSetsBehavior
moveNode() protectedMoves the owner subtree to the position described by the context, within its tree or into another tree.NestedSetsBehavior
moveNodeAsRoot() protectedPromotes the owner subtree to a new tree identified by the owner primary key and closes the gap it leaves.NestedSetsBehavior
shiftLeftRightAttribute() protectedAdds the delta to every left and right value greater than or equal to the given value within the owner tree.NestedSetsBehavior
ConstantValueDescriptionDefined 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
public function acquireTreeLock(): void

Acquires 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, $lockTimeout is out of range, the nested_sets_lock registry is missing, or the lock wait times out.
public function afterDelete(): void

Closes the gap left by the deleted owner, moving the children of a node deleted on its own one level up.

Throws

public function afterInsert(): void

Assigns 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.
public function afterRefresh(): void

Clears cached coordinates after a model refresh without cancelling an active operation.

public function afterUpdate(): void

Moves the owner subtree to the position requested by the pending operation and reloads the owner coordinates.

Throws

public function appendTo(yii2\extensions\nestedsets\T $node, bool $runValidation = true, list<string>|null $attributes = null): bool

Appends 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

ParameterTypeDescription
$nodeyii2\extensions\nestedsets\TNode that becomes the parent of the owner.
$runValidationboolWhether to validate the owner before saving.
$attributeslist<string>|nullAttributes 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.
public function beforeDelete(): void

Acquires the table writer lock, reloads the owner coordinates, and rejects deleting a root node on its own.

Throws

public function beforeInsert(): void

Reloads the target coordinates and assigns the coordinates of the new owner according to the pending operation.

Throws

public function beforeUpdate(): void

Reloads 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 $treeAttribute is false, 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.
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

ParameterTypeDescription
$depthint|nullMaximum 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.

public function deleteWithChildren(): bool|int

Deletes 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.
public function events(): string[]

Returns the ActiveRecord lifecycle event handlers of the behavior.

Returns

string[]: The event handlers of the behavior.

public function insertAfter(yii\db\ActiveRecord $node, bool $runValidation = true, list<string>|null $attributes = null): bool

Places 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

ParameterTypeDescription
$nodeyii\db\ActiveRecordNode that becomes the previous sibling of the owner.
$runValidationboolWhether to validate the owner before saving.
$attributeslist<string>|nullAttributes 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.
public function insertBefore(yii\db\ActiveRecord $node, bool $runValidation = true, list<string>|null $attributes = null): bool

Places 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

ParameterTypeDescription
$nodeyii\db\ActiveRecordNode that becomes the next sibling of the owner.
$runValidationboolWhether to validate the owner before saving.
$attributeslist<string>|nullAttributes 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.
public function invalidateCache(): void

Clears the cached coordinates and discards the pending operation and target node.

public function isChildOf(yii\db\ActiveRecord $node): bool

Returns whether the owner is a descendant of the given node within the same tree.

Parameters

ParameterTypeDescription
$nodeyii\db\ActiveRecordCandidate ancestor of the owner.

Returns

bool: Whether the owner lies strictly inside the boundaries of the node and shares its tree identifier.

public function isLeaf(): bool

Returns whether the owner has no descendants.

Returns

bool: Whether the right value of the owner exceeds its left value by exactly 1.

public function isRoot(): bool

Returns whether the owner is a root node.

Returns

bool: Whether the left value of the owner is 1.

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.

public function makeRoot(bool $runValidation = true, list<string>|null $attributes = null): bool

Makes 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

ParameterTypeDescription
$runValidationboolWhether to validate the owner before saving.
$attributeslist<string>|nullAttributes 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.
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.

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

ParameterTypeDescription
$depthint|nullMaximum 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.

public function prependTo(yii\db\ActiveRecord $node, bool $runValidation = true, list<string>|null $attributes = null): bool

Prepends 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

ParameterTypeDescription
$nodeyii\db\ActiveRecordNode that becomes the parent of the owner.
$runValidationboolWhether to validate the owner before saving.
$attributeslist<string>|nullAttributes 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.
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.

protected function beforeInsertNode(int $value, int $depth): void

Assigns the coordinates of a new child or sibling at the given position and opens space for it in the tree.

Parameters

ParameterTypeDescription
$valueintLeft value of the new node.
$depthintDepth offset relative to the target node: 0 for a sibling, 1 for a child.

Throws

protected function beforeInsertRootNode(): void

Assigns root coordinates to a new owner.

Throws

protected function moveNode(yii2\extensions\nestedsets\NodeContext $context): void

Moves the owner subtree to the position described by the context, within its tree or into another tree.

Parameters

ParameterTypeDescription
$contextNodeContextTarget position and depth offset of the move.
protected function moveNodeAsRoot(mixed $treeValue): void

Promotes the owner subtree to a new tree identified by the owner primary key and closes the gap it leaves.

Parameters

ParameterTypeDescription
$treeValuemixedIdentifier of the tree that currently contains the subtree.
protected function shiftLeftRightAttribute(int $value, int $delta): void

Adds the delta to every left and right value greater than or equal to the given value within the owner tree.

Parameters

ParameterTypeDescription
$valueintLowest boundary value to shift, inclusive.
$deltaintSigned offset to add; a negative value closes a gap.