Project using Nest.js/E-commerce App

TypeORM의 @ManyToOne과 @OneToMany

Cog Factory 2021. 9. 3. 17:38

개요

   TypeORM은 관계형 ORM이다. 각각의 인스턴스가 서로를 참조할 수 있다.

product.entity.ts

import { Field, InputType, ObjectType } from '@nestjs/graphql';
import { IsString } from 'class-validator';
import { Column, Entity, ManyToOne } from 'typeorm';

import { CoreEntity } from 'src/common/entities/common.entity';
import { Category } from 'src/categories/entities/category.entity';

@InputType('ProductInputType', { isAbstract: true })
@ObjectType()
@Entity()
export class Product extends CoreEntity {
  @Column()
  @Field((type) => String)
  @IsString()
  name: string;

  @ManyToOne((type) => Category, (category) => category.products, {
    onDelete: 'SET NULL',
  })
  @Field((type) => Category)
  category: Category;
}

  Product 여러 개가 하나의 category를 가리키고 있으므로 @ManyToOne을 사용한다.

category.dto.ts

import { Field, InputType, ObjectType } from '@nestjs/graphql';
import { IsString, MinLength } from 'class-validator';
import { CoreEntity } from 'src/common/entities/common.entity';
import { Product } from 'src/products/entities/product';
import { Column, Entity, OneToMany } from 'typeorm';

@InputType('CategoryInputType', { isAbstract: true })
@ObjectType()
@Entity()
export class Category extends CoreEntity {
  @Field((type) => String)
  @Column({ unique: true })
  @IsString()
  @MinLength(1)
  name: string;

  @Field((type) => [Product])
  @OneToMany((type) => Product, (products) => products.category)
  products: Product[];
}

   반면에 하나의 category는 여러 개의 products를 가리키므로 @OneToMany를 사용한다. 이로써 서로의 instance를 가리키게 된다.

참고자료