본문 바로가기
NestJS

TypeORM - 다대다 관계 구현

by Programmer.Junny 2025. 2. 24.

다대다 관계는 포스트된 글과 태그의 관계를 생각해볼 수 있다.

포스팅된 글에 여러 태그들이 달릴 수 있으며, 태그들 또한 여러 글에 존재할 수 있다.

다만 정규화된 테이블끼리 직접 연결은 데이터베이스에선 불가능하다. 

그리고 이것을 해결하기 위해 '중간 테이블' 이라는 개념이 존재한다.

중간 테이블

import { Column, Entity, JoinTable, ManyToMany, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { UserModel } from "./user.entity";
import { TagModel } from "./tag.entity";

@Entity()
export class PostModel {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(() => UserModel, (user) => user.posts)
    author: UserModel;

    @ManyToMany(() => TagModel, (tag) => tag.posts)
    @JoinTable()
    tags: TagModel[];

    @Column()
    title: string;
}
@ManyToMany(() => TagModel, (tag) => tag.posts)
@JoinTable()
tags: TagModel[];

포스트부터 살펴보면 위와 같이 설정할 수 있다. @ManyToMany()

조금 다른 점은 TagModel[] 배열로 받은 점이다.

import { Column, Entity, ManyToMany, PrimaryGeneratedColumn } from "typeorm";
import { PostModel } from "./post.entity";

@Entity()
export class TagModel {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToMany(() => PostModel, (post) => post.tags)
    posts: PostModel[];

    @Column()
    name: string;
}

마찬가지로 태그도 @ManyToMany() 로 설정한다.

 

'NestJS' 카테고리의 다른 글

TypeORM - where 유틸리티  (0) 2025.02.25
TypeORM - FindManyOptions 파라미터  (0) 2025.02.24
TypeORM - 일대다, 다대일 관계 구현  (0) 2025.02.24
TypeORM - 일대일 관계 구현  (0) 2025.02.24
Entity Embedding VS Table Inheritance  (0) 2025.02.24

최근댓글

최근글

skin by © 2024 ttuttak