노드 학습 19일차
안녕하세요 🐸
오늘은 multer 를 사용하여 파일 업로드 및 제어를 공부했습니다.
multer 미들웨어를 공부하고 사용해보면서 인터페이스와 공식 문서를 보고 분석한 내용은 아래의 글에 정리해봤습니다.
오늘 학습 중 과거 시퀄라이즈 모델에 대해 공부하면서 놓치고 있었던 부분이 있어 다시 정리하고자 합니다.
문제
belongsTo 한 테이블에 생기는 컬럼의 이름은 어떻게 디폴트 값을 가지는가?
풀이
시퀄라이즈 모델간의 관계를 명시하는 함수에는 다음과 같은 함수가 있습니다.
- hasOne
- hasMany
- belongsTo
- blongsToMany 여기서 저는 belongsTo 의 사용에 대해 정리하고자 합니다.
예시 상황)
User 모델과 Comment 모델이 있을 때 사용자는 N개의 댓글을 가질 수 있지만 댓글의 작성자는 1명입니다.
그렇기 때문에 User와 Commet 는 1:N 관계입니다.
이 때 두 모델의 관계는 아래와 같이 사용합니다.
- User는 Comment 를 hasOne 합니다.
- Comment는 User를 belongsTo 합니다.
Comment 에서 belongsTo 하면 실제 DB의 comment 테이블에는 관련한 컬럼이 추가가 됩니다.
belongsTo() 인터페이스를 참조해보면 아래와 같습니다.
1
2
3
4
5
6
7
8
9
10
11
12
/**
* Creates an association between this (the source) and the provided target. The foreign key is added on the
* source.
*
* Example: `Profile.belongsTo(User)`. This will add userId to the profile table.
*
* @param target The model that will be associated with hasOne relationship
* @param options Options for the association
*/
public static belongsTo<M extends Model, T extends Model>(
this: ModelStatic<M>, target: ModelStatic<T>, options?: BelongsToOptions
): BelongsTo<M, T>;
이때, belongsTo 에는 두 가지 파라미터를 전달할 수 있습니다.
- target - 연결할 모델
- options - 옵션
상속 구조를 따라가보면 options 의 타입인 BelongsToOptions
은 AssociationOptions
를 확장한 타입인 것을 확인할 수 있습니다.
드디어 여기에 문제의 원인이 옵션이 있습니다.
- foreignKey`
foreignKey는 해당 테이블에서 외래 키를 참조하는 컬럼입니다.
실질적으로 targetKey를 참조하게 됩니다.
기본 값은 대상 모델명 + 대상 모델 primary Key 입니다.
원문은 아래와 같습니다.
1
2
3
4
5
6
/**
* The name of the foreign key in the target table or an object representing the type definition for the
* foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property
* to set the name of the column. Defaults to the name of source + primary key of source
*/
foreignKey?: string | ForeignKeyOptions;
해답
모델간의 관계를 정의하면서 옵션 중에 foreignKey 를 명시하지 않으면 테이블에 추가되는 컬럼의 이름은 모델명 + 모델의 primary key 가 된다.