병신같은 시퀄라이즈

codeing999·2022년 8월 20일
1

Sequelize 사용 일지

목록 보기
5/10

저번주에 시퀄라이즈로 디비 설계 완벽하게 해서 만족했는데
이번주에 그 방법 기록해두고 그대로 했는데 안먹힌다.

이새끼는 노드1주차 때 첫인상부터 맘에 안들었는데 또 이럴줄 알았다.

암튼 새벽내내 검색해보고 물어보고 해서 겨우 다시 되는 방법 찾음.
2개 찾음.

해결 방법1

npx sequelize-cli migration:generate --name user-like-association
npx sequelize-cli migration:generate --name user-dislike-association

이와 같이 새로운 마이그래이션을 만들고 그 각각에 아래와 같은 외래키 추가하는 내용 작성.

"use strict";

module.exports = {
  async up(queryInterface, Sequelize) {
    queryInterface.addConstraint("Likes", {
      fields: ["userId"],
      type: "foreign key",
      name: "Like_People_asociation",
      references: {
        table: "Users",
        field: "userId",
      },
    });
  },

  async down(queryInterface, Sequelize) {
    queryInterface.removeConstraint("Likes", {
      fields: ["userId"],
      type: "foreign key",
      name: "Like_People_asociation",
      references: {
        table: "Users",
        field: "userId",
      },
    });
  },
};

워크벤치로 확인해봐도 외래키 잘 생성되어있었다.
근데 아래 방법이 더 간단해서 아래방법을 쓰고 있음.

해결 방법2

userId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: "Users",
          key: "userid",
        },
      },

마이그레이션 파일에다가 이와같이 작성.
이건 Users테이블의 userId를 참조하는 Likes 테이블의 마이그래이션 파일이다. 근데 실수로 userid에 i 소문자로 썼는데도 되긴 됐네.
model:이라고 써있지만 저기엔 테이블 명을 쓰는것이다.
그리고 워크벤치에서 보면 외래키 들어가긴 하는데
cascade가 안되어 있다.
references: {
model: "Users",
key: "userid",
onUpdate: "cascade",
onDelete: "cascade",
},
이렇게 넣어봤지만 그래도 안먹힘. 이건 그냥 워크벤치로 캐스캐이드해야겠다

참고 자료

https://www.youtube.com/watch?v=XvCcyqB96Yg //1번 방법
https://stackoverflow.com/questions/53146054/foreign-key-with-sequelize-not-working-as-expected //2번 방법

https://velog.io/@cadenzah/sequelize-document-2 //시퀄라이즈 쿼리함수들 자세한거.

profile
코딩 공부 ing..

1개의 댓글

comment-user-thumbnail
2022년 9월 14일

이제 생각이 달라 지셨나요?

2022-09-15, 항해99 동료

답글 달기