如何使用 TypeORM 将新节点添加到已使用 table 闭包的 children 的节点?

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

我正在尝试使用 typeorm and follow this example 来处理分层数据结构这个例子只是关于如何创建一个层次结构 table 并读取它的路径但是当我们已经有了一个节点时呢有 children,我们想添加更多 children 我相信我们应该能够推动这样的事情:

category.children.push(newCategory);

但是 category.children 是空的,而它有 children。

编辑 1:

代码如下:

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));
}

结果如下: 第一个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
}

第二个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 }
]

您是否在 @TreeChildren() 装饰器上添加了 { cascadeInsert: true, cascadeUpdate: true } 选项?你如何加载 category ?如果你通过 QueryBuilder 加载它,你可能会忘记使用 leftJoinAndSelect 方法加入孩子。