【问题标题】:Join Tables in TypeORM & NodeJS在 TypeORM 和 NodeJS 中加入表
【发布时间】:2020-05-06 00:01:04
【问题描述】:

我创建了 TypeORM 实体类别和子类别

Category.ts

@Entity()
export class Category {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  description: string;

  @OneToMany(() => Subcategory, (subcategory) => subcategory.category)
  public Subcategories: Subcategory[];

  @OneToMany(() => Item, (item) => item.category)
  public Items: Item[];

}

Subcategory.ts

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  OneToMany,
  CreateDateColumn,
  UpdateDateColumn
} from "typeorm";
import {Category} from "./Category";
import {Item} from "./Item";

@Entity()
export class Subcategory {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  description: string;

  @ManyToOne(() => Category, (category) => category.Subcategories)
  public category: Category;

  @OneToMany(() => Item, (item) => item.subcategory)
  public Items: Item[];

}

在 TypeScript 上获取类别查询:

await getRepository(Category).find();

问题:

我无法在线找到将子类别包含到 getCategory 查询中的方法,我只需执行一个简单的连接即可获得所有类别及其子类别。在实体框架中,我曾经使用过 Category.Includes(Subcategories) 之类的东西,它可以完成这项工作。

在 TypeORM / NodeJS 中加入表格是否有任何简单/简单的方法?

非常感谢您花时间阅读我的问题,非常感谢!

【问题讨论】:

    标签: javascript node.js typescript mean typeorm


    【解决方案1】:

    在查阅了不同的教程后,我发现这种方式非常适合我的需要:

    const categories = await getRepository(Category).find({relations: ['Subcategories']});
    

    【讨论】:

    • 非常感谢!!对我来说效果很好!
    【解决方案2】:
    const categories = await getRepository(Category).createQueryBuilder("ct").
    innerJoinAndSelect("ct.Subcategories", "sb").getMany()
    

    参考以下文档
    https://typeorm.io/#/select-query-builder

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2021-02-06
      • 2021-12-12
      • 2020-04-05
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      相关资源
      最近更新 更多