codestates / codestates/Almost-There
[Error log] migration이 되지 않음(sequelize) / 2022-02-17
- Dominant language
- TypeScript
- Stars
- 0
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
### 어떤 에러인가요?
- 테이블 간 관계가 설정한 대로 MySQL에 반영되지 않는 문제
- sequelize migration이 되지 않는 문제
(sequelize로 원하는 테이블의 필드에 foreign key를 설정할 수 없는 문제)
### 에러 메시지
```bash
$ Loaded configuration file "config/config.js".
Using environment "development".
== 20220217062950-fk-comment: migrating =======
ERROR: Failed to add the foreign key constraint. Missing index for constraint 'user_id_fk' in the referenced table 'users_groups'
```
### 에러 핸들링 방법
- migration 파일을 생성하여 테이블 설정 추가하기
(`queryInterface.addConstraint` 메소드 사용)
- 참조하고자 하는 값의 타입을 Unique로 지정
(참조하고자 하는 값의 타입이 Primary key 또는 Unique 타입이어야 migration이 됨)
- 연결되는 두 값의 데이터 타입을 동일하게 변경
(연결하는 두 필드의 타입이 동일해야한다고 함)
```js
async up (queryInterface, Sequelize) {
await queryInterface.addConstraint('users', {
fields: ['userId'],
type: 'unique',
name: 'users_userId_unique'
});
await queryInterface.addConstraint('users_groups', {
fields: ['userId'],
type: 'foreign key',
name: 'user_id_fk',
references: {
table: 'users',
field: 'userId'
},
onDelete: 'cascade',
onUpdate: 'cascade'
});
}
```

### 에러 핸들링을 위해 참고한 레퍼런스 링크
[[1822] Failed to add the foreign key constraint MySQL에러](https://yusang.tistory.com/104)
[Node Sequelize ORM 다루기 - 외래키 생성하기, 관계형 설정하기](https://loy124.tistory.com/374)
[Sequelize API Reference](https://sequelize.org/master/class/src/dialects/abstract/query-interface.js~QueryInterface.html#instance-method-addConstraint)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.