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!
@JoinTable options @JoinTable is used for many-to-many relations and describes join columns of the "junction" table. A junction table is a special separate table created automatically by TypeORM with columns that refer to the related entities.
TypeORM has a method called innerJoinAndSelect . You use plain innerJoin . That is why user table is not selected from. Once you change that part to innerJoinAndSelect , watch table will be selected from.
Relations are used to refer the relationship between table in database. In general, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table. This feature makes relational database more powerful and efficiently store information.
QueryBuilder is one of the most powerful features of TypeORM - it allows you to build SQL queries using elegant and convenient syntax, execute them and get automatically transformed entities. Simple example of QueryBuilder : const firstUser = await dataSource.
After looking up different tutorials I found that this way worked perfectly for my need:
const categories = await getRepository(Category).find({relations: ['Subcategories']});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With