【问题标题】:How to load relations with tree entity with typeorm?如何使用 typeorm 加载与树实体的关系?
【发布时间】:2019-07-19 02:22:00
【问题描述】:

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

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

[{
  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[]
}

【问题讨论】:

    标签: typeorm


    【解决方案1】:

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

    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"
                        }
                    ]
                }
            ]
        }
    

    【讨论】:

    • 这并不能解决问题。存储库是一个树存储库,您的解决方案仅在第一级加入。所有其他子路由都不会加入。但是你如何获得每个子路由的角色呢?
    【解决方案2】:

    我认为获取关系的正确方法是何时创建树实体:

    await getManager().getTreeRepository(Route).findTrees({ relations: ["roles"] });
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 1970-01-01
      • 2021-12-27
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2021-03-08
      • 2021-10-27
      相关资源
      最近更新 更多