TypeORM: How ownership side works?

Viewed 202

Suppose we have two models Profile and User:

import {Entity, PrimaryGeneratedColumn, Column, OneToOne} from "typeorm";
import {User} from "./User";

@Entity()
export class Profile {
    
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column()
    gender: string;
    
    @Column()
    photo: string;
    
    @OneToOne(() => User, user => user.profile) // specify inverse side as a second parameter
    user: User;
    
}
import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from "typeorm";
import {Profile} from "./Profile";

@Entity()
export class User {
    
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column()
    name: string;
    
    @OneToOne(() => Profile, profile => profile.user) // specify inverse side as a second parameter
    @JoinColumn()
    profile: Profile;
    
}

I want have bi-directional relation between these two models and it works, I can find Profile from User and vice versa. However when I ran SHOW CREATE TABLE profile there was no reference whatsoever to User model! Then how does it work? How can I find join User from Profile side?

Does it affect the performance which side is the owner? If not, What is the point of thinking about which side to put @joinColumn?

1 Answers

As you found, the User definition in the database has no reference to Profile because there is no @JoinColumn on the User Table. It is the @JoinColumn that defines the foreign-key relationship in the database. The @OneToOne is used my TypeOrm to generate metadata and queries, but it does not affect the database schema.

Note: You can only have @JoinColumn on one side of the relation.

If it is a true one-to-one relationship, it does not matter which side you put the @JoinColumn.

If it's possible to have a Profile row without a matching User row, the @JoinColumn has to be on User.

Related