포스트

노드 학습 20일차

안녕하세요 🐸

오늘도 시퀄라이즈와 관련해 모르는 부분이 있어서 정리합니다.

문제

시퀄라이즈에서 모델간의 관계를 정의하면 생기는 함수는 단수/복수의 관계를 어떻게 처리하는가?

풀이

사용자가 서로 팔로우 하는 기능을 만들고 배우는 중, 아래와 같이 모델의 관계를 정의 했습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//생략
    static associate(db){
        db.User.hasMany(db.Post);
        db.User.belongsToMany(db.User,{ // 팔로워 -> 나를 팔로우 하는 사람
            foreignKey : 'followingId', // 팔로우 당하는 사람
            as : 'Followers', // 팔로우 하는 사람들
            through : 'Follow'
        });
        db.User.belongsToMany(db.User,{ // 팔로잉 -> 내가 팔로우 하는 사람
            foreignKey : 'followerId', // 팔로우 하는 사람
            as : 'Followings', // 팔로우 당하는 사람 
            through:'Follow'
        }); 
    }
}

여기서 belongsToMany() 를 통해 User 객체는 다음의 함수들을 가지게 됩니다.

  • as : 'Followers' 구문을 통해 생성되는 함수
    • getFollowers()
    • countFollowers()
    • addFollower()
    • addFollowers()
    • setFollowers()
    • hasFollower()
    • hasFollowers()
    • removeFollower()
    • removeFollowers()
    • createFollower()
  • as : 'Followings' 구문을 통해 생성되는 함수
    • getFollowings()
    • countFollowings()
    • addFollowing()
    • addFollowings()
    • setFollowings()
    • hasFollowing()
    • hasFollowings()
    • removeFollowing()
    • removeFollowings()
    • createFollowing()

시퀄라이즈는 위와 같이 모델 간의 관계를 정의하면 관계형 쿼리 함수를 생성합니다.
예시로 사용한 belongsToMany() 와 동일하게 hasOne() , hasMany() , belongsTo() 도 동일하게 함수를 생성하며, 각각의 관계가 어떤 종류의 함수를 생성하는지는 공식 문서에 있습니다.

참조한 공식 문서 내용 : https://sequelize.org/docs/v6/core-concepts/assocs/?utm_source=chatgpt.com#special-methodsmixins-added-to-instances

여기서 저는 어떻게 시퀄라이즈가 내가 전달한 값이 복수형인지 단수형인지를 구분하고 함수를 생성하는지가 궁금했습니다.

해답

sequelize 는 내부적으로 inflection 라는 라이브러리를 통해 단어의 복수/단수를 파악하고 함수를 생성합니다.
불규칙 복수 명사도 inflections 라이브러리 내에 정의 되어 있기 때문에 대부분의 경우 라이브러리를 통해 단수/복수를 판단하고 변환하줍니다.
그리고 sequelize 는 이 결과를 통해 함수를 생성합니다.


참조 : https://sequelize.org/docs/v6/core-concepts/assocs/#special-methodsmixins-added-to-instances

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.