Search code examples
ajaxjquery-nestable

sortable & Nestable Category how can i send it to server?


Hello i use Sortable & Nestable structure how can i save this data to database with php. It's enough for me if you can provide a resource to guide me.

My Data :

[
    {
        "id": "1",
        "children": [
            {
                "id": "2",
                "children": [
                    {
                        "id": "3"
                    },
                    {
                        "id": "4"
                    },
                    {
                        "id": "5"
                    },
                    {
                        "id": "6"
                    },
                    {
                        "id": "7"
                    },
                    {
                        "id": "8"
                    },
                    {
                        "id": "9"
                    },
                    {
                        "id": "10"
                    }
                ]
            },
            {
                "id": "11",
                "children": [
                    {
                        "id": "12"
                    },
                    {
                        "id": "14"
                    },
                    {
                        "id": "13"
                    },
                    {
                        "id": "15"
                    },
                    {
                        "id": "16"
                    }
                ]
            }
        ]
    }
]

My Database structure : Database Table Thanks in advance for your help.

I'm trying to save this data to the database but I can't. I searched on the internet but couldn't find enough results. I will be very happy if you help me


Solution

  • You can iterate the tree recursively keeping track of current parent, then pushing to db each of its children as child - parent.

    var tree = [{id:"1",children:[{id:"2",children:[{id:"3"},{id:"4"},{id:"5"},{id:"6"},{id:"7"},{id:"8"},{id:"9"},{id:"10"}]},{id:"11",children:[{id:"12"},{id:"14"},{id:"13"},{id:"15"},{id:"16"}]}]}];
    
    var db = [];
    
    function iterate(children, parent) {
      parent = parent || 0;
      children.forEach(function(child) {
        db.push ({child: child.id, parent: parent})
        if (child.children) {
          iterate(child.children, child.id)
        }
      })
    }
    
    iterate(tree)
    
    console.log(db)