상권's
TIL 41 (sequelize association)(2021.11.21) 본문
Associations
Sequelize는 '1 대 1', '1 대 다', '다 대 다' 관계를 지원합니다.
The A.hasOne(B.foreign key) association
A와 B의 '1 대 1' 관계를 만들어 주는데, foreign key는 B에서 정의된다.
The A.belongsTo(B) association
A와 B의 '1대 1' 관계를 만들어 주는데, foreign key는 A에서 정의된다.
The A.hasMany(B) association
A와 B의 '1 대 다' 관계를 만들어 주는데, foreign key는 B에서 정의된다.
이 세 가지 호출을 통해 Sequilize는 적절한 모델에 외래 키를 자동으로 추가한다(이미 존재하지 않는 경우).
The A.belongsToMany(B, { through: 'C' }) association
A와 B 간에 '다 대 다' 관계를 C 테이블을 이용해서 만들어 주며, 외래 키(예: aId 및 bId)가 있음을 의미한다. Sequialize는 이 모델 C를 자동으로 생성하고 모델 C에 적절한 외래 키를 정의한다.
사용 예시
앞 번에 만들었던 urls 에다가 userId라는 행을 하나 더 만들고, 이 행을 통해서 users 라는 테이블과 join할 수 있도록 foreign 키를 설정해보도록 하겠습니다.
아래의 2번째 코드처럼 migration을 하나 더 만들어줍니다.
그리고 이를 통해서 addColumn과 addConstraint를 진행합니다.
'use strict';
// npx sequelize-cli migration:generate --name migration-skeleton 를 통해서
// migration을 하나 만들어주고, 열 추가와, 제약 추가를 진행한다.
// The passed queryInterface object can be used to modify the database.
// The Sequelize object stores the available data types such as STRING or INTEGER.
// Function up or down should return a Promise. Let's look at an example:
module.exports = {
up: async (queryInterface, Sequelize) => {
queryInterface.addColumn('urls', 'userId', Sequelize.INTEGER)
// urls에 userId라는 열을 하나 더 만든다.
queryInterface.addConstraint('urls', {
// 제약을 하나 만든다.
fields: ['userId'],
type: 'foreign key',
name: 'user is connected with url',
// 참조를 만들어 준다
references: {
table: 'users',
field: 'id'
},
onDelete: 'cascade',
onUpdate: 'cascade'
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeConstraint('urls', 'user is connected with url');
await queryInterface.removeColumn('urls', 'userId');
}
};
users라는 테이블이 만들어지면,
url의 model 부분에 아래와 같이 static associate 부분에 관계에 대해서 정의해줍니다.
module.exports = (sequelize, DataTypes) => {
class url extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
models.url.belongsTo(models.user);
}
};
user도 아래와 같이 associate를 정의해줍니다.
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
// user는 url에 일 대 다 관계임을 만들어준다.
models.user.hasMany(models.url);
}
};
'~2022 작성 글 > TIL' 카테고리의 다른 글
TIL 43 (token-based authentication, jwt) (2021.11.23) (0) | 2021.11.23 |
---|---|
TIL 42 (CSRF, session, HTTPS)(2021.11.22) (0) | 2021.11.23 |
TIL 40 (NoSQL, MongoDB, Aggregation)(2021.11.19) (0) | 2021.11.19 |
TIL 39 (sequelize, ORM) (2021.11.18) (0) | 2021.11.18 |
TIL 38 (과제리뷰, should, supertest)(2021.11.17) (0) | 2021.11.17 |