본문으로 바로가기

Sequelize.js Association belongsTo 정리

category Coding/Node.js 2018. 7. 15. 23:29
반응형

개인적으로 ORM을 사용하는건 굉장히 불편하다.

SQL Statement에 익숙하지 않은 사람들은 ORM을 통해 사용하는 언어의 형태로 쉽게 작성이

가능하여 편하다고 느껴진다고 하는데, 나같은 경우에는 그냥 SQL문으로는 이렇게 하면 되겠지라고

쉽게 생각이 들어도 ORM에 맞춰서 코드를 작성하려고 하다 보면 어려웠다.

또한 오늘은 Sequelize.js에 대해 작성하는 글이지만 이전에 장고를 사용하면서

사용했던 ORM은 또 그것만의 문법이 존재했다.

튼, 요즘에는 Node.js를 공부하고 있는데 데이터베이스와 통신하기 위해 Sequelize.js를 사용하고 있고

관계 설정에 대한 부분이 헷갈리는 부분이 조금씩 존재하여 아예 그냥 통번역을 해버리기로 했다.

본 포스팅은 http://docs.sequelizejs.com/manual/tutorial/associations.html에서 belongsTo() 부분만 번역한 글이다.


Associations

이번 장에서는 Sequelize의 다양한 관계에 대해 설명할 것이다. 예를 들어 User.hasOne(Project)라는 메소드를 호출했다고 가정하면,

User모델을 source라고 하고 Project모델을 target이라고 한다.


One-To-One associations

1:1 관계란 정확히 두개의 모델에서 1:1로 매칭되는 관계이다.


BelongsTo

BelongsTo association은 외래키가 소스 모델에 존재한다. 아래의 예제를 살펴보면

Player모델의 외래키는 Team모델의 일부가 되는 것을 알 수 있다.

const Player = this.sequelize.define('player', {/* attributes */});
const Team  = this.sequelize.define('team', {/* attributes */});

Player.belongsTo(Team); // Player모델에서 Team의 PK를 가지고 있기 위해 teamId라는 컬럼이 추가된다

Foreign keys

기본적으로 belongsTo 관계에서 외래키는 target의 주키의 이름과 모델을 통해 자동적으로 생성된다.

별다른 설정이 없다면 camelCase로 생성되지만 underscored: true 속성을 준다면 camel_case 형태로 생성된다.

const User = this.sequelize.define('user', {/* attributes */})
const Company  = this.sequelize.define('company', {/* attributes */});

User.belongsTo(Company); // User모델에 companyId가 추가된다

const User = this.sequelize.define('user', {/* attributes */}, {underscored: true})
const Company  = this.sequelize.define('company', {
  uuid: {
    type: Sequelize.UUID,
    primaryKey: true
  }
});

User.belongsTo(Company); // User모델에 company_uuid가 추가된다


as속성을 통해 target 모델의 이름을 정해줄 수 있다.

const User = this.sequelize.define('user', {/* attributes */})
const UserRole  = this.sequelize.define('userRole', {/* attributes */});

User.belongsTo(UserRole, {as: 'role'}); // User모델에 userRoleId라는 컬럼대신 roleId 컬럼이 추가된다

모든 경우에서 기본 외래키는 foreignKey 옵션을 통해 새롭게 정의할 수 있다.

foreignKey 옵션이 사용된다면 Sequelize는 해당 옵션을 사용할 것이다.

const User = this.sequelize.define('user', {/* attributes */})
const Company  = this.sequelize.define('company', {/* attributes */});

User.belongsTo(Company, {foreignKey: 'fk_company'}); // User모델에 fk_company가 추가된다


Target keys

target 키는 source모델의 외래키에서 가르키고 있는 target의 컬럼이다.

기본적으로 belongsTo의 target 키는 target 모델의 주키가 된다.

이것을 바꾸고 싶다면 아래와 같이 targetKey 옵션을 사용하면 된다.

const User = this.sequelize.define('user', {/* attributes */})
const Company  = this.sequelize.define('company', {/* attributes */});

User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // User모델에 fk_companyname가 추가된다


반응형