我尝试使用typeorm并按照this example来处理分层数据结构,示例只是关于如何创建层次结构表并阅读它的路径但是什么关于什么时候我们已经有一个有孩子的节点,我们想要添加更多的孩子,我相信我们应该能够推送这样的东西:
category.children.push(newCategory);
但是category.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));
}
结果如下: 第一个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 }
]
答案 0 :(得分:0)
您是否在{ cascadeInsert: true, cascadeUpdate: true }
装饰器上添加了@TreeChildren()
个选项?你如何加载category
?如果您通过QueryBuilder
加载,则可能会忘记使用leftJoinAndSelect
方法加入chidrens。