public function setDepthWithSubtree()
{
$self = $this;
$this->getConnection()->transaction(function () use($self) {
$self->reload();
$self->descendantsAndSelf()->select($self->getKeyName())->lockForUpdate()->get();
$oldDepth = !is_null($self->getDepth()) ? $self->getDepth() : 0;
$newDepth = $self->getLevel();
$self->newNestedSetQuery()->where($self->getKeyName(), '=', $self->getKey())->update([$self->getDepthColumnName() => $newDepth]);
$self->setAttribute($self->getDepthColumnName(), $newDepth);
$diff = $newDepth - $oldDepth;
if (!$self->isLeaf() && $diff != 0) {
$self->descendants()->increment($self->getDepthColumnName(), $diff);
}
});
return $this;
}