public function insertAsFirstChildOf(TreeModel &$parentNode)
{
if ($parentNode->lft >= $parentNode->rgt) {
throw new TreeInvalidLftRgtParent();
}
// Get a reference to the database
$db = $this->getDbo();
// Get the field names
$fldRgt = $db->qn($this->getFieldAlias('rgt'));
$fldLft = $db->qn($this->getFieldAlias('lft'));
// Nullify the PK, so a new record will be created
$this->{$this->idFieldName} = null;
// Get the value of the parent node's rgt
$myLeft = $parentNode->lft;
// Update my lft/rgt values
$this->lft = $myLeft + 1;
$this->rgt = $myLeft + 2;
// Update parent node's right (we added two elements in there, remember?)
$parentNode->rgt += 2;
// Wrap everything in a transaction
$db->transactionStart();
try {
// Make a hole (2 queries)
$query = $db->getQuery(true)->update($db->qn($this->tableName))->set($fldLft . ' = ' . $fldLft . '+2')->where($fldLft . ' > ' . $db->q($myLeft));
$db->setQuery($query)->execute();
$query = $db->getQuery(true)->update($db->qn($this->tableName))->set($fldRgt . ' = ' . $fldRgt . '+ 2')->where($fldRgt . '>' . $db->q($myLeft));
$db->setQuery($query)->execute();
// Insert the new node
$this->save();
// Commit the transaction
$db->transactionCommit();
} catch (\Exception $e) {
// Roll back the transaction on error
$db->transactionRollback();
throw $e;
}
return $this;
}