DevMachine
DevMachine

Reputation: 563

Join Tables in TypeORM & NodeJS

I created to TypeORM Entities Category and Subcategory

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[];

}

Get Category Query on TypeScript :

await getRepository(Category).find();

Issue:

I couldn't find a way online to include the Subcategories into the getCategory query, I just one to perform a simple join that will get me All the categories and their subcategories. In entity framework I used to something like Category.Includes(Subcategories) and it does the job.

Is there any easy/simple way to join tables in TypeORM / NodeJS ?

Thanks a lot for taking the time to read my question, I appreciate it!

Upvotes: 11

Views: 22999

Answers (2)

const categories = await getRepository(Category).createQueryBuilder("ct").
innerJoinAndSelect("ct.Subcategories", "sb").getMany()

Refer to the following documentation
https://typeorm.io/#/select-query-builder

Upvotes: 0

DevMachine
DevMachine

Reputation: 563

After looking up different tutorials I found that this way worked perfectly for my need:

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

Upvotes: 14

Related Questions