Sequelize 모델에 필드추가!

9rganizedChaos·2021년 3월 3일
1
post-thumbnail

클라이언트가 없이 진행되는 스프린트다 보니, 눈으로 확인하기가 어려워서 사실 Sequelize에 등장하는 개념들을 명확히 이해하는 게 조금 어렵다...

어드밴스드 과제인 "Associations을 이용한 Join Table 구현"을 시도하고 성공(?)하였지만,
이걸 어디에 어떻게 쓰는지가 아직 감이 안 온다 (눈물)
일단 과제 수행과정을 공유한다.

일단 미션 소개를 간단히 하면,

url을 단축시켜주는 어플리케이션이 있다.
기존에 어플리케이션의 서버는 url이란 테이블이 마련된 데이터베이스와 소통한다.
url 테이블에는 "id", "url", "title", "visits", "createdAt", "updatedAt"이 존재!

Mission1: user 테이블 추가
Mission2: url 테이블에 userId 필드 추가

users 모델과 addUserIdColums 마이그레이션파일 추가


(사실 여기까지는 호용님께서 미리 힌트를 주셨다.)

Mission1: user 테이블 추가

이건 간단한 미션이었음...
유저 테이블은 자유롭게 디자인하라고 하셔서 최대한 간단하게 이름과 이메일만 넣었다.
이름만 넣을까도 고민했지만, 나도 양심이 있으니까 이메일까지는 추가...

npx sequelize-cli model:generate --name user --attributes name:string,email:string

물론 이거 하나 추가하라고 어드밴스드 과제를 주셨을리는 없으므로...

Mission2: url 테이블에 userId 필드 추가

여기서부터 조금씩 헤메기 시작했다!

씨퀄라이즈 명령어 도움말을 살펴보면 모델생성과 마이그레이션 생성이따로 존재한다.
단순히 필드를 추가하기 위해서는 모델을 생성할 필요는 없다.
모델의 경우 어차피 어트리뷰트를 입력해주지 않으면 에러가 뜬다!
단순히 테이블의 필드를 관리하기 위한 마이그레이션파일을 생성하기 원한다면,
아래와 같이 입력해야 했다.

sequelize migration:generate --name AddUserIdColumn

Migration 파일 up/down 메소드 작성!

Sequelize add column 이런 식으로 검색하면...
이런 아름다운 공식문서와 어떤 천사분께서 공유해주신 삽질 후기가 검색된다...

up: addColumn()

// sequelize db:migrate를 실행하시 up이 실행됨
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn("urls", "userId", {
      type: Sequelize.INTEGER,
      references: { model: "users", key: "id" },
      // 참조하고 있는 프라이머리 키의 값이 변했을 때 영향을 받는 과정
      onUpdate: "CASCADE",
      onDelete: "CASCADE",
    });
    //urls에 userId 필드 추가
    //userId를 FK로 지정
    /**
     * Add altering commands here.
     *
     * Example:
     * await queryInterface.createTable('users', { id: Sequelize.INTEGER });
     */
  },

down: removeColumn()

  // sequelize db:migrate:undo를 실행하시 down이 실행됨
  down: async (queryInterface, Sequelize) => {
    return queryInterface.removeColumn("urls", "userId");
    // userId를 FK해제
    // urls에 userId필드 삭제
    /**
     * Add reverting commands here.
     *
     * Example:
     * await queryInterface.dropTable('users');
     */
  },

사실 컬럼을 없앨 때, 왜 FK해제를 먼저 따로 해줘야하는지 잘 모르겠다...

RESULT


업데이트 아이디 밑에 userId라는 쁘띠한 테이블이 생성되었다.

모델파일 Association 정의!

url.js

    static associate(models) {
      // define association here
      url.belongsTo(models.user, {
        foreignKey: "userId",
      });
    }

user.js

    static associate(models) {
      // define association here
      user.hasMany(models.url);
    }

이 부분을 따로 정의해주는 건 왜?

사실 이 부분을 따로 작성하지 않아도 씨퀄프로에서 테이블 확인이 가능하던데
이걸 왜 해주는 거지... 하는 궁금증이 생겼다.

공식문서에 따르면...

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).

라고 합니다. 조인테이블... 즉, 테이블간 참조... 씨퀄라이즈에서는 테이블 간의 참조 관계를 정의해주면서 어쏘시에이션이 완성된다고 설명하는 것 같다...

관계를 정의할 때는 다음과 같은 키워드를 호출한다!

  • hasOne - adds a foreign key to the target and singular association mixins to the source.
  • belongsTo - add a foreign key and singular association mixins to the source.
  • hasMany - adds a foreign key to target and plural association mixins to the source.
  • belongsToMany - creates an N:M association with a join table and adds plural association mixins to the source. The junction table is created with sourceId and targetId.

사실 아직 레퍼런스 코드를 확인하거나,
이 서버(?)를 통해 실습과정을 거치지 못해서 좀 더 보완해야 할 듯 싶다...
우선 중간점검차 여기까지 작성해서 기록한다!

profile
부정확한 정보나 잘못된 정보는 댓글로 알려주시면 빠르게 수정토록 하겠습니다, 감사합니다!

0개의 댓글