본문 바로가기
Node.js/TypeORM

One-to-one relations

by Ykie 2023. 4. 14.
728x90

A가 오로지 하나의 B만 포함한다! B역시 오직 하나의 A만 포함한다.
https://typeorm.io/one-to-one-relations


One-to-one is a relation where A contains only one instance of B, and B contains only one instance of A. Let's take for example User and Profile entities. User can have only a single profile, and a single profile is owned by only a single user.

// Profile
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Profile {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    gender: string

    @Column()
    photo: string
}


// 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)
    @JoinColumn()
    profile: Profile
}

Here we added @OneToOne to the user and specify the target relation type to be Profile. We also added @JoinColumn which is required and must be set only on one side of the relation. The side you set @JoinColumn on, that side's table will contain a "relation id" and foreign keys to target entity table.

 

one-to-one은 잘 없다. 대부분 one-to-many, many-to-one 혹은 many-to-many 이다.

728x90

'Node.js > TypeORM' 카테고리의 다른 글

TypeOrm  (0) 2023.04.06

댓글