【问题标题】:How to join every child entity in a tree structure in typeorm如何在typeorm中加入树结构中的每个子实体
【发布时间】:2021-07-28 08:37:55
【问题描述】:

我有一个类别的树形结构。这些类别与其他表有关系。

import {Entity, Column, PrimaryGeneratedColumn, ManyToOne, OneToMany} from "typeorm";
@Entity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    description: string;

    @ManyToOne(type => Category, category => category.children)
    parent: Category;

    @OneToMany(type => Category, category => category.parent)
    children: Category[];

    @OneToMany(type => Site, site => site.category)
    sites: Site[];
}

我获取树的代码:

console.log(await getConnection().getTreeRepository(Category).findTrees());

结果:

[
  Category {
    pk: 8,
    id: '1C606380-020A-4CED-8EBA-AA1C9C16FCF2',
    title: 'Category EXPLICIT',
    createdBy: 'SAFETYMANUAL',
    createdAt: 2021-07-27T19:57:03.213Z,       
    hidden: false,
    orderValue: 0,
    deletionDate: null,
    childCategories: [ [Category] ]
  }
]

我想用关系加载整个树,在本例中是 Sites 数组。将 eager 设置为 true 不会改变任何事情。我只取回没有站点数组的树。是否有可能加入树结构?

【问题讨论】:

  • 嘿,我也无法加载树中的关系。你找到解决办法了吗?
  • @rickster 我实现了一个拉取请求,可以加载关系。我为我的问题添加了答案。希望对您有所帮助。

标签: javascript typescript orm typeorm typeorm-activerecord


【解决方案1】:

我实现了一个拉取请求,可以为树加载关系:

const treeCategoriesWithRelations = await repository.findTrees({ relations: ["sites"] });
// automatically joins the sites relation

【讨论】:

  • 最新版本的 Nest 是否可用,即 8.1.1 ?因为我无法使用它。它给了我错误。 Expected 0 arguements. Recieved 2这样的
  • @rickster 可能还没有在 Nest 中可用 - 这是一个相当新的功能,但在最新的 typeorm 版本中发布。 Nest 可能还没有更新到最新的 typeorm 版本。
  • 哦,好吧。谢谢。
猜你喜欢
  • 2021-10-27
  • 1970-01-01
  • 2021-07-23
  • 2017-05-07
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多