TypeORM 공식문서 에 따르면
ManyToMany 인 경우에 두 entity를 연결해줄 새로운 entity를 만들어 어야 한다고 한다.
예를 들어 Category 와 Post 가 many-to-many 관계를 가지면 PostToCategory 를 만들어서 두 엔티티를 연결해라고 적혀있다. 즉, Category: PostToCategory ( 1 : N), Post : PostToCategory (1 : N) 와 같이 만들어서 연결을 해야한다.
Entity 구성 예시
Category.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from "typeorm"
import { PostToCategory } from "./PostToCategory"
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany(() => PostToCategory, (postToCategory) => postToCategory.category)
postToCategories: PostToCategory[];
}
Post.entity.ts
import {Column, Entity, OneToMany, PrimaryGeneratedColumn} from "typeorm";
import {PostToCategory} from "./PostToCategory.entity";
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id : number;
@Column()
title: string;
@Column()
content: string;
@OneToMany(() => PostToCategory, (postToCategory) => postToCategory.post)
postToCategories: PostToCategory[];
}
PostToCategory.ts
import {Entity, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
import {Post} from "./Post.entity";
import {Category} from "./Category.entity";
@Entity()
export class PostToCategory {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(() => Post, (post) => post.postToCategory)
post : Post;
@ManyToOne(() => Category, (category) => category.postToCategory)
category : Category;
}
위의 코드를 작성하고 생성된 엔티티들의 관계를 보면
옆 의 그림과 같이 관계도가 형성된다.
데이터 생성 및 관계 저장
공식문서에서는 아래와 같이 하면 관계가 형성된다고 했지만....
const question = new Question()
question.categories = [category1, category2]
entity 를 생성할때 아래와 같이 하지 않아서 관계가 형성이 안된다고 판단
그리고 데이터를 저장할때 배열의 형식으로 저장을 하려면 배열의 개수만큼 필드를 추가해야한다.
@ManyToMany(() => Category)
@JoinTable()
categories: Category[]
그래서 아래와 같은 시나리오를 생각하여 적용해보았다.
- category 들이 이미 생성되어 있다.
- post 를 게시했다.
- post 를 게시하는 중에 category 목록에서 선택
- post data 와 category 데이터가 post-category entity에 전송!!
async createRelation(createRelationRequestDto:CreateRelationRequestDto): Promise<any> {
const {post, categories} = createRelationRequestDto;
let allRelations = []
for ( const category of categories){
let relation = await this.postCateogryRepository.save({category, post})
allRelations.push(relation)
}
return allRelations
}
데이터 조회
post.service.ts 에 구현
async find(): Promise<Post[]>{
const foundPosts = await dataSource.getRepository(Post).find({
relations: {
postToCategories: {
category: true,
},
},
});
// 데이터 정제를 위한 로직
const posts = foundPosts.map((post) => {
const categories = post.postToCategories.map(
(postToCategory) => postToCategory.category,
);
delete post.postToCategories;
return {
...post,
categories,
};
});
return posts
}
데이터 삭제
F.K. 에 연결되어 있는 것을 먼저 삭제한 후 삭제 하는 방식
post-category 에 있는 데이터 삭제 후 post 삭제 가능
'프로그래밍 > Nest.js' 카테고리의 다른 글
[ NestJS ] [ TypeORM ] DB 삭제, 수정, 생성 시간 남기기 (0) | 2024.04.29 |
---|---|
[ NestJS] [ TypeORM ] transactions - DataSource 이용 (0) | 2024.04.29 |
[ NestJS ] [ TypeORM ] 1: N 관계 형성, 수정, 삭제 (0) | 2024.04.27 |
[ NestJS] [errror] No metadata for "User" was found. (0) | 2024.04.23 |
[ NestJS ] Modules (0) | 2024.04.18 |