Dish entity

김종민·2022년 7월 4일
0

Nuber-Server

목록 보기
24/34


들어가기
restaurant에 따른 menu 즉, Dish Entity
어려울것 없이 Entity간의 관계만 유심히 본다
restaurant module에 다 같이 만든다.

1. dtos/dish.entity

import { Field, InputType, Int, ObjectType } from '@nestjs/graphql';
import { IsNumber, IsString, Length } from 'class-validator';
import { CoreEntity } from 'src/common/entities/core.entity';
import { Column, Entity, ManyToOne, RelationId } from 'typeorm';
import { Restaurant } from './restaurant.entity';

@InputType('DishChoiceInputType', { isAbstract: true })
@ObjectType()
class DishChoice {
  @Field(() => String)
  name: string;

  @Field(() => Int, { nullable: true })
  extra?: number;
}

@InputType('DishOptionInputType', { isAbstract: true })
@ObjectType()
class DishOption {
  @Field(() => String)
  name: string;

  @Field(() => [DishChoice], { nullable: true })
  choices?: DishChoice[];

  @Field(() => Int, { nullable: true })
  extra?: number;
}
///Dish에 따른 options를 DishOption[]로 만들어줌.
///예를 들어 포테이토 피자의 매운맛, 중간맛, 등등.
// choices는 매운맛을 골랐다면, 그에 따른, size. XL, L, S등등

@InputType('DishInputType', { isAbstract: true })
@ObjectType()
@Entity()
export class Dish extends CoreEntity {
  @Field(() => String)
  @Column({ unique: true })
  @IsString()
  @Length(5)
  name: string;

  @Field(() => Int)
  @Column()
  @IsNumber()
  price: number;

  @Field(() => String, { nullable: true })
  @Column({ nullable: true })
  @IsString()
  photo: string;

  @Field(() => String)
  @Column()
  @Length(5, 150)
  description: string;

  @Field(() => Restaurant)
  @ManyToOne(() => Restaurant, (restaurant) => restaurant.menu, {
    onDelete: 'CASCADE', //식당이 지워지면, menu도 다 지워져야 되니까 CASCADE를 쓴다.
  })
  restaurant: Restaurant;
  ///여러개의 Dish는 하나의 restaurant를 가진다.
  ///식당을 지우면, menu도 다 사라진다.( CASCADE)

  @RelationId((dish: Dish) => dish.restaurant)
  restaurantId: number;
  ///dish를 부를떄, 관련 restaurant로 불러야 될 경우가 많아서 RelationId를 붙인다.

  @Field(() => [DishOption], { nullable: true })
  @Column({ type: 'json', nullable: true })
  options?: DishOption[];
  ///options들은 type을 'json'으로 한다.
  ///따른 Entity로 만들어 봐도 된다.
  
}

type:'json'형태를 확인한다.

profile
코딩하는초딩쌤

0개의 댓글