'ello all.
I've been reading http://www.sitepoint.com/article/hierarchical-data-database/3/ and have a functioning tree that I can add to or delete from. I am having trouble figuring out the algorithm to update the tree when a node is moved.
Here is the method I am using ... I am sure it is something obvious.
Any assistance would be great ... my mind is fried and it's only noon. :bemused:
public function updateRole(array $data, $where, array $old){
$this->db->beginTransaction();
try {
// if left or right values altered
if($data['lft'] != $old['lft']){
// parent updated
$parent = $this->getParentByLFT($data['lft']);
if(!is_array($parent)){
$parent['lft'] = $parent['rght'] = 0;
}
// update lft
$this->db->query("UPDATE `".$this->_name."` SET `lft` = `lft` + 1 WHERE `lft` > ".$parent['lft']);
// update rght
$this->db->query("UPDATE `".$this->_name."` SET `rght` = `rght` + 1 WHERE `rght` < ".$parent['rght']);
// update rght
$this->db->query("UPDATE `".$this->_name."` SET `rght` = `rght` + 2 WHERE `rght` >= ".$parent['rght']);
}
// replace $data['lft'] with parent lft + 1
$data['lft'] = $parent['lft'] + 1;
// replace $data['rght'] with parent rght - 1
$data['rght'] = $parent['rght'] - 1;
// update record
$this->db->update($this->_name, $data, $where);
$this->db->commit();
return true;
} catch(Exception $e){
$this->db->rollBack();
throw new Exception($e->getMessage());
}
}
I saw the function used in the link above, but I don't want to traverse the tree to update it (unless that's the only way).
TIA!
edit
Before this method is run, the tree is intact. Afterwards the tree is borked on both lft and rght.
roleid lft rght role_name
1 1 10 Administrator
2 3 10 Member
3 5 6 Guest
10 2 7 Test