Sequelize 관계 정의하기

2023. 7. 9. 20:47ORM/Sequelize

테이블 간의 관계에는 1:N, 1:1, N:M 이 있다.

1:N

사용자 모델은 게시글 모델과 1:N 관계를 가지고 있다.

모델의 1:N 관계를 설정할 때는 model.hasMany, model.belongsTo 2가지의 메서드를 사용한다. 만약 모델 간의 관계를 설정한 경우 foreignKey 에 해당하는 컬럼이 belongsTo 메서드를 사용하는 모델에 생성되게 된다.

 

/* user.js */

    static associate(db) {
        db.User.hasMany(db.Comment, { foreignKey: 'commenter', sourceKey: 'id', onDelete: 'cascade', onUpdate: 'cascade' });
        // db.User (hasMany) db.Comment = 1:N 관계 이다.
        // 남(db.Comment)의 컬럼 commenter가 내(db.User) 컬럼 id를 참조 하고 있다.  
    }
};
// comment.js

    static associate(db) {
        db.Comment.belongsTo(db.User, { foreignKey: 'commenter', targetKey: 'id', onDelete: 'cascade', onUpdate: 'cascade'});
        // db.Comment (belongTo) db.User = N:1 관계 이다.
        // 내(db.Comment)의 컬럼 commenter는 남(db.User) 컬럼 id에 속해 있다.  
    }
};

 

보통 외래키가 붙은 테이블이 belongsTo 가 된다.

 


1:1

사용자 모델은 사용자 정보 모델과 1:1 관계를 가진다.

1:1 관계를 설정할 때는 hasOne, belongsTo 2가지의 메서드를 사용한다.

만약 모델간의 관계를 설정한 경우 foreignKey 에 해당하는 참조하는 컬럼이 belongsTo 메서드를 사용하는 모델에 생성되게 된다.

// models/users.js

// 1. Users 모델에서
this.hasOne(models.UserInfos, { // 2. UserInfos 모델에게 1:1 관계 설정을 합니다.
  sourceKey: 'userId', // 3. Users 모델의 userId 컬럼을
  foreignKey: 'UserId', // 4. UserInfos 모델의 UserId 컬럼과 연결합니다.
});
// models/userInfos.js

// 1. UserInfos 모델에서
this.belongsTo(models.Users, { // 2. Users 모델에게 1:1 관계 설정을 합니다.
  targetKey: 'userId', // 3. Users 모델의 userId 컬럼을
  foreignKey: 'UserId', // 4. UserInfos 모델의 UserId 컬럼과 연결합니다.
});

N:M

테이블과 해시태그 (#) 테이블 관계는 N:M 관계가 있다.

N:M 관계를 belongsToMany 메서드로 표현한다.

이 경우에는 어느 한 테이블이 어느 다른 테이블에 종속되는 관계가 아니다.

// Post
db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag' });

// Hashtag
db.Hashtag.belongsToMany(db.Post, { through: 'PostHashtag' });

 

N:M 관계 특성상 새로운 모델이 생성되며, through 속성에 그 이름을 적으면 된다.

새로 생성된 PostHashtag 모델에는 게시글과 해시태그의 아이디가 저장된다.

 

'ORM > Sequelize' 카테고리의 다른 글

Sequelize 관계 쿼리  (0) 2023.07.09
Sequelize CRUD 쿼리  (0) 2023.07.09
Sequelize Model  (0) 2023.07.09
Sequelize Migration  (0) 2023.07.09
Sequelize 라이브러리 구성  (0) 2023.07.09