Search code examples
hierarchical-datatypeorm

How to use TypeORM to add new node to a node that already has children using table closure?


I'm trying to use typeorm and follow this example to deal with hierarchical data structure the example is only about how to create a hierarchy table and read it's path but what about when already we have a node that has children and we want to add more children to I believe we should be able to push something like this:

category.children.push(newCategory);

but category.children is empty while it has children.

Edit1:

Here is the code:

async function test() {
    let connection = await createConnection(options);
    let categoryRepository = connection.getTreeRepository(Category);
    let cat = await categoryRepository.findOneById(4, {
        relations: ['children']
    });
    console.log(JSON.stringify(cat));
    let childChildCategory1 = new Category();
    childChildCategory1.name = "Child #1 of Child #1 of Category #11111";
    childChildCategory1.description = "Child #1 of Child #1 of Category #11111";
    cat["__children__"].push(childChildCategory1)
    await categoryRepository.save(cat);
    let result = await categoryRepository.findDescendants(cat);
    console.log(JSON.stringify(result));
}

and here is the result: The first console.log:

{
    "id":4,
        "name":"Child #2 of Category #1",
            "description":"Child #2 of Category #1",
                "level":2,
                    "__children__":[
                        { "id": 5, "name": "Child #1 of Child #2 of Category #1", "description": "Child #1 of Child #2 of Category #1", "level": 3 },
                        { "id": 6, "name": "Child #1 of Child #1 of Category #11111", "description": "Child #1 of Child #1 of Category #11111", "level": 3 },
                        { "id": 7, "name": "Child #1 of Child #1 of Category #11111", "description": "Child #1 of Child #1 of Category #11111", "level": 3 }
                    ],
                        "__has_children__":true
}

The second console.log:

[
    { "id": 4, "name": "Child #2 of Category #1", "description": "Child 
    #2 of Category #1", "level": 2 },
    { "id": 5, "name": "Child #1 of Child #2 of Category #1", 
    "description": "Child #1 of Child #2 of Category #1", "level": 3 },
    { "id": 6, "name": "Child #1 of Child #1 of Category #11111", 
    "description": "Child #1 of Child #1 of Category #11111", "level": 
    3 },
    { "id": 7, "name": "Child #1 of Child #1 of Category #11111", 
    "description": "Child #1 of Child #1 of Category #11111", "level": 
    3 },
    { "id": 8, "name": "Child #1 of Child #1 of Category #11111", 
    "description": "Child #1 of Child #1 of Category #11111", "level": 
    3 }
]

Solution

  • Did you put { cascadeInsert: true, cascadeUpdate: true } options on @TreeChildren() decorator ? How do you load the category ? If you load it through QueryBuilder, you may forgot join the chidrens with leftJoinAndSelect method.