According to the documentation, in TypeORM a relationship is defined as follows: A user has exactly one profile.
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;
}
Issue
When creating a new user, why do I have to pass a complete instance of the entity (profile: Profile) instead of - as usual - only one ID? Like this:
@OneToOne(type => Profile)
@JoinColumn()
profileId: number;
Isn't there another way?
This procedure causes a large, unnecessary overhead, if you have to make 4 queries for 4 foreign keys to get the corresponding instance instead of the ID.
I would be very grateful for help to get around this!
In TypeORM the navigation field (here profile
) can be combined with the plain foreign key field (profileId
). So you can write:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(type => Profile)
@JoinColumn()
profile: Profile;
@Column()
profileId: number;
}
Then it's up to you if you update the relation with the entity object or only with the profile id.