1、create a new table. tree_folder(id, id_folder, tree_id)
2、create a new table. tree(id, tree_json)
The tree
table maintain a whole tree node. For example, the following tree with a root node 1
.
{
"folder_id": 1,
"parent_folder_id": 0,
"children": [
{
"folder_id": 10,
"parent_folder_id": 1,
"children": null
},
{
"folder_id": 11,
"parent_folder_id": 2,
"children": null
}
]
}
The table contains this row.
[id, tree_json]
[1, "xxxxx"]
Then maintain the relation between the node and tree. As you can see the tree contains the node 1
, 10
, 11
. Then we have the table tree_folder
.
[id, folder_id, tree_id]
[1, 1 , 1]
[2, 10 , 1]
[3, 11 , 1]
When you need get the folder 10
's tree. just get from the tree, then deal it in you program.
In this way, you just do recursion in memory instead of mysql.
That is you should maintain the structure when write the data, but the query is easy and fast. If the query is frequent, this works fine. But if the write is frequent, just use a cache instead of this method.