My question is what is the right approach to delete a node in a nested model set using PHP and MYSQL. As far as i am concern, i have to decrement all left values greater than the node to delete’s left value by 2..However i am so confuse with the next steps. You answers will be very much appreciated.
This is my function:
public function deleteNode($id,$left,$right)
{
//?
}
I just found the solutions from Mike Hillyers
public function delete_node($id)
{
$query = $this->db->query("
SELECT node.label
FROM menus AS node,menus AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rft AND parent.id = $id
GROUP BY node.label
ORDER BY node.lft
");
if($query->num_rows() > 1)
{
$this->db->trans_start();
$this->db->query("LOCK TABLE $this->table WRITE");
$this->db->query("SELECT @myLeft := lft, @myRight := rft, @myWidth := rft - lft + 1 FROM $this->table WHERE id = $id");
$this->db->query("DELETE FROM $this->table WHERE lft = @myLeft");
$this->db->query("UPDATE $this->table SET rft = rft - 1, lft = lft - 1 WHERE lft BETWEEN @myLeft AND @myRight");
$this->db->query("UPDATE $this->table SET rft = rft - 2 WHERE rft > @myRight");
$this->db->query("UPDATE $this->table SET lft = lft - 2 WHERE lft > @myRight");
$this->db->query("UNLOCK TABLES");
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
return false;
}
else
{
return true;
}
}
else
{
$this->db->trans_start();
$this->db->query("LOCK TABLE $this->table WRITE");
$this->db->query("SELECT @myLeft := lft, @myRight := rft, @myWidth := rft - lft + 1 FROM $this->table WHERE id = $id");
$this->db->query("DELETE FROM $this->table WHERE lft BETWEEN @myLeft AND @myRight");
$this->db->query("UPDATE $this->table SET rft = rft - @myWidth WHERE rft > @myRight");
$this->db->query("UPDATE $this->table SET lft = lft - @myWidth WHERE lft > @myRight");
$this->db->query("UNLOCK TABLES");
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
return false;
}
else
{
return true;
}
}
}