删除 MYSQL 中的循环 parent/child

Get rid of circular parent/child in MYSQL

我有一个 table 这样的:

 Attribute  |  Type   | Modifier
------------+---------+----------
 id         | integer | not null
 title      | text    | not null
 parent     | integer | 

parent 字段是引用相同 table 的外键。

如何确保不插入循环(循环 parent/child 引用)?例如:

 id         | title   | parent
------------+---------+----------
 1          | A       | 3 or 2
 2          | B       | 1
 3          | C       | 2

我正在使用 PHP 和 MySQL。

首先,假设 table 最初没有循环。如果是这样,那么您将需要手动修复任何循环。然后,当您尝试为 child 设置 parent 时,首先获取 child 的潜力 parent。然后继续获取 parent 的 parent。如果你到达一个没有parent的节点,那么一切正常,你可以设置child的parent。如果你到达 child,那么你知道如果你设置 parent.

就会创建一个循环
function canSetParent($child, $parent)
{
    $node = $parent;
    while($node != null)
    {
        if($node->id == $child->id) return false;  //Looped back around to the child
        $node = $node->parent;
    }
    return true;  //No loops found
}