簡體   English   中英

復制樹結構遞歸-鄰接表模型

[英]Copy tree structure recursive - Adjacency List Model

我嘗試將樹結構從一個數據庫表復制到另一個數據庫表。 該結構是鄰接表模型。 看起來像:

id|parent_id|position
1|0|1
2|1|1
3|1|2
4|0|2
5|4|1 

必要在另一個表中重新生成ID(自動遞增)! 我具有以下功能:

/**
 * Copy a single node and return the new id
 */
public function copyNode($sn_data){
    $this->db2->insert('items_configurations', $sn_data);
    return $this->db2->insert_id();
}

/**
 * Return a list of child nodes as an assoziative array
 * from a given parent
 */
public function childList($parent_id){
    $tmp  = 'SELECT parent_id,item_id,template_id,position FROM items_templates WHERE parent_id='.$parent_id;
    $tmp .= ' ORDER BY position';
    $query=$this->db2->query($tmp);
    return $query->result_array();
}

/**
 * Copy the whole tree structure through an recursive function
 */
public function copyTree($node_data,$given_parent){
    $new_parent = $this->copyNode($node_data);
    $new_data   = $this->childList($node_data['id']);
    if(is_array($new_data)){
        foreach($new_data as $new_node_data) :
            $new_node_data['parent_id'] = $given_parent;
            $new_node_data['configuration_id'] = $node_data['configuration_id'];
            $this->copyTree($new_node_data,$new_parent);
        endforeach;
    }
}


/**
 * First call of the function for example:
 */    
$this->copyTree(array('parent_id' => 0,'item_id' => 40,'template_id' => 6,'position' => 1),0);

我想遞歸執行,但是它只復制前兩行。 錯誤在哪里?

1.遞歸遍歷時,必須使用當前節點id作為parent_id。 您正在childList中使用它的parent_id:

parent_id='.$parent_id;

必須為parent_id ='。$ id;

您得到的是該節點的同級節點,然后是子節點。

2.我也對標記的行表示懷疑:

if(is_array($new_data)){
    foreach($new_data as $new_node_data) :
        $new_node_data['parent_id'] = $new_parent;//<--
        $this->copyTree($new_node_data);
    endforeach;
}

因為您有一個新的parent_id,然后將它與childList函數中的舊表一起使用。 檢查參數是否正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM