Relations FAQ
Sometimes you want to have in your object id of the related object without loading it.For example:
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number;
@Column()
gender: string;
@Column()
photo: string;
}
import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from "typeorm";
import {Profile} from "./Profile";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(type => Profile)
@JoinColumn()
profile: Profile;
}
When you load a user without profile
joined you won’t have any information about profile in your user object,even profile id:
But sometimes you want to know what is the “profile id” of this user without loading the whole profile for this user.To do this you just need to add another property to your entity with @Column
named exactly as the column created by your relation. Example:
import {Profile} from "./Profile";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ nullable: true })
profileId: number;
@OneToOne(type => Profile)
@JoinColumn()
profile: Profile;
}
That’s all. Next time you load a user object it will contain a profile id:
User {
id: 1,
name: "Umed",
}
Alternative and more flexible way is to use QueryBuilder
:
const user = await connection
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.profile", "profile")
.leftJoinAndSelect("user.photos", "photo")
.leftJoinAndSelect("user.videos", "video")
Using QueryBuilder
you can do innerJoinAndSelect
instead of leftJoinAndSelect
(to learn the difference between LEFT JOIN
and INNER JOIN
refer to your SQL documentation),you can join relation data by a condition, make ordering, etc.
Learn more about QueryBuilder
.
Sometimes it is useful to initialize your relation properties, for example:
import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from "typeorm";
import {Category} from "./Category";
@Entity()
export class Question {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
text: string;
@ManyToMany(type => Category, category => category.questions)
@JoinTable()
categories: Category[] = []; // see = [] initialization here
}
Now when you save this object categories
inside it won’t be touched - because it is unset.
But if you have initializer, the loaded object will look like as follow:
Question {
id: 1,
title: "Question about ...",
}
When you save the object it will check if there are any categories in the database bind to the question -and it will detach all of them. Why? Because relation equal to []
or any items inside it will be consideredlike something was removed from it, there is no other way to check if an object was removed from entity or not.
Therefore, saving an object like this will bring you problems - it will remove all previously set categories.