얼음꽃의 일지

[JS] Sequelize Association(관계) 설정 본문

잡다한 지식

[JS] Sequelize Association(관계) 설정

얼음꽃 2023. 11. 8. 16:50
728x90

Sequelize에서 간단하게 관계 설정 하는 법을 적으려고 합니다.

 

기본적인 코드는 다음과 같습니다.

 

// 모델 안에서 진행한다는 가정하에 진행합니다.

table_name.model.js

table_name.associate = (models) => {
	table_name.hasMany(models.other_table_name, {
    	foreignKey : "fields",
        sourceKey : "fields",
       });
}


other_table_name.model.js

other_table_name.associate = (models) => {
	other_table_name.belongsTo(models.table_name, {
    	foreignKey : "fields",
        targetKey : "fields",
       });
}

 

association은 1:1 1:M M:N 종류가 있습니다.

 

1:1 은 hasOne - belongsTo

1:M 은 hasMany - belongsTo

M:N 은 belongsToMany

 

로 묶이게 됩니다.

 

보통 처음 하는 분들은 어떤걸 앞에 두고 뒤에다 둬야하는지 헷갈릴 수 있습니다.

 

위의 코드를 통해 설명 드리면

 

각 모델에서 association 관계를 할 associate 파트를 만들고

 

이제 서로 묶을 모델을 설정하면되는데요. 영어로 봤을때 이렇게 이해 하시면 됩니다.

 

table_name hasMany other_table_name : table_name은 많은 other_table_name 을 가지고있다.

other_table_name belongsTo table_anem : other_table_name은 table_name에 속해있다.

 

이렇게 보면 table_name은 other_table_name을 많이 가지고 있으니 1이되고

 

그 많은 other_table_name이 table_name에 속해있으니 M으로 보시면 됩니다.

 

foreginKey, sourceKey, targetKey는 각각 해당하는 테이블에 맞춰지는 키 값들을 의미합니다.

 

추가 적인 내용은 sequelize 보시면 좀 더 확실하게 알 수 있습니다.

 

https://sequelize.org/docs/v6/core-concepts/assocs/

 

Associations | Sequelize

Sequelize supports the standard associations: One-To-One, One-To-Many and Many-To-Many.

sequelize.org

 

728x90