如何使用typeorm加载与树实体的关系?

时间:2019-07-19 02:22:00

标签: typeorm

我有一个角色实体和一个树状结构的路由实体,它们是ManyToMany关系。

现在,我想通过RoleRepository.find({relations:['routes']})检索所有角色,它将按预期加载所有角色数据,但是route属性不会自动加载其子数据,看起来像:

[{
  id: 1,
  name: 'route1',
  routes: [{
    id: 1,
    path: '/home'
  }]
}]

我已经检查了所有文档,没有线索。

@Entity()
export class Role {
  @PrimaryGeneratedColumn()
  public id: number

  ... some other columns

  @ManyToMany(type => Route, route => route.roles)
  public routes: Route[]
}
@Entity()
@Tree('materialized-path')
export class Route {
  @PrimaryGeneratedColumn()
  public id: number

  @TreeParent()
  public parent: Route

  @TreeChildren({ cascade: true })
  public children: Route[]

  @ManyToMany(type => Role, role => role.routes)
  @JoinTable()
  public roles: Role[]
}

1 个答案:

答案 0 :(得分:0)

要加载关系的子级,您只需在关系数组中添加所需的属性,如下所示:

RoleRepository.find({relations: ['routes', 'routes.roles']})

它应该给你类似的东西

"route": {
        "id": 1,
        "name": "route1",
        "roles": [{
                "id": 1,
                "name": "role1",
                "routes": [{
                        "id": 1,
                        "name": "route1"
                    }, {
                        "id": 2,
                        "name": "route2"
                    }
                ]
            }
        ]
    }
相关问题