0

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

category.children.push(newCategory);

但是 category.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 }
]
4

1 回答 1

0

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

于 2017-12-08T06:03:55.933 回答