wam
w__am 개발노트
wam
  • 분류 전체보기 (165)
    • CS 지식 (10)
      • 자료구조 (0)
      • 알고리즘 (0)
      • 컴퓨터 구조 (0)
      • 운영체제 (0)
      • 네트워크 (7)
      • 데이터베이스 (0)
      • 디자인 패턴 (3)
    • Frontend (131)
      • Three.js (64)
      • NPM (1)
      • Nest.js (19)
      • React (10)
      • Apollo (7)
      • TypeScript (2)
      • JavaScript (12)
      • HTML, CSS (1)
      • Jest (3)
      • E2E (5)
      • Cypress (7)
    • Database (12)
      • TypeORM (12)
    • IT 지식 (8)
      • 클라우드 서비스 (3)
      • 네트워크 (1)
      • 데이터 포맷 (2)
      • 기타 (2)
    • IT Book (2)
    • 유용한 사이트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 🐱 Github

인기 글

태그

  • 렌더링 성능 최적화
  • 삼각함수
  • 초기 환경설정
  • 함수의 범위
  • Decorators
  • gridhelper
  • getelapsedtime()
  • 디자인 패턴
  • type-graphql
  • API
  • 스코프
  • math.cos()
  • axeshelper
  • getdelta()
  • react 성능 최적화
  • 함수 표현식
  • mapped types
  • threejs 개발 할 때 도움을 줄 수 있는 유틸리티
  • Interface
  • 오프-프레미스(off-premise) 방식
  • 원형적인 움직임
  • math.sin()
  • reactive variables
  • three.js 구성 요소
  • 데이터 포맷
  • isabstract
  • joi 에러
  • e.preventdefault()
  • 함수 리터럴
  • 함수 선언문

최근 글

관리자

글쓰기 / 스킨편집 / 관리자페이지
hELLO · Designed By 정상우.
wam

w__am 개발노트

Column 타입 JSON으로 지정, @Column({ type: "json" })
Database/TypeORM

Column 타입 JSON으로 지정, @Column({ type: "json" })

2024. 8. 2. 20:44

 

@Column({ type: "json" })

  • TypeORM에서 JSON 형식의 데이터를 데이터베이스 열(column)에 저장할 때 사용하는 데코레이터이다.
  • JSON 데이터는 복잡한 구조를 가지며, 다양한 유형의 데이터를 포함할 수 있다.
  • type: "json"을 지정하면, 해당 열에 JSON 형식의 데이터를 저장하고 쿼리할 수 있다.
  • 구조화된 데이터를 저장하거나, 특정 형태를 가진 데이터를 저장해야 할 때 json type을 사용한다.
  • 복잡한 데이터일 경우 Entity에 넣지 않고 json 타입으로 저장하기도 한다.
  • json은 MySQL, PostgreSQL에서 지원하는 데이터 타입이다.

 

 

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

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

    @Column({ type: "json" })
    settings: any; // JSON 형식의 데이터를 저장할 필드
}
  • @Column({ type: "json" }) 이 데코레이터는 데이터베이스 열이 JSON 형식의 데이터를 저장하도록 설정
  • settings: any settings 필드는 JSON 형식의 데이터를 저장한다. TypeScript의 any 타입을 사용하면 JSON 데이터의 구조가 유동적일 때 유용하다.

 

 

객체의 배열을 JSON 형식으로 저장

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()
export class DishChoice {
  @Field(() => String)
  name: string;

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

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

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

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

@InputType("DishInputType", { isAbstract: true })
@ObjectType()
@Entity()
export class Dish extends CoreEntity {
  @Field(() => String)
  @Column()
  @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, 140)
  description: string;

  @Field(() => Restaurant)
  @ManyToOne(() => Restaurant, (restaurant) => restaurant.menu, {
    onDelete: "CASCADE",
  })
  restaurant: Restaurant;

  @RelationId((dish: Dish) => dish.restaurant)
  restaurantId: number;

  @Field(() => [DishOption], { nullable: true })
  @Column({ type: "json", nullable: true })
  options?: DishOption[];
}
  • options 필드는 DishOption 객체의 배열을 JSON 형식으로 저장할 수 있도록 설정
  • Dish 엔티티의 options 필드가 JSON 형식으로 데이터베이스에 저장
  • JSON 형식으로 저장하면, DishOption 객체의 배열을 쉽게 저장하고 조회할 수 있다.

 

 

 

저작자표시 변경금지

'Database > TypeORM' 카테고리의 다른 글

Relations 정리 Many-to-Many, @JoinTable()  (0) 2024.08.06
@RelationId, 특정 필드에 대한 외래 키 값만 가져오기  (0) 2024.08.02
Relations 정리 One-to-One, @JoinColumn()  (0) 2024.08.02
Relations 정리 OneToMany, ManyToOne  (0) 2024.08.02
EntityRepository - deprecated 되었다.  (0) 2024.08.02
    'Database/TypeORM' 카테고리의 다른 글
    • Relations 정리 Many-to-Many, @JoinTable()
    • @RelationId, 특정 필드에 대한 외래 키 값만 가져오기
    • Relations 정리 One-to-One, @JoinColumn()
    • Relations 정리 OneToMany, ManyToOne
    wam
    wam

    티스토리툴바