시퀄라이즈(3)

올챙이·2024년 9월 3일

Node.js

목록 보기
21/23
post-thumbnail

시퀄라이즈 사용하기

관계 정의하기

  • users 테이블과 comments 테이블 간의 관계를 정의했습니다.

  • 사용자 한 명은 댓글을 여러 개 작성할 수 있습니다.

  • 댓글 하나에 사용자가 여러 명일 수는 없습니다.

  • 일대다(1:N) 관계라고 합니다.

  • 사용자가 1, 댓글이 N입니다.

1:N

  • hasMany

    • users 테이블의 로우 하나를 불러올 때 연결된 comments 테이블의 로우를 가져옵니다.
  • belongsTo

    • comments 테이블의 로우를 불러올 때 연결된 users 테이블의 로우를 가져옵니다.
  • 코드

    • user.js
      1
      2
      3
          static associate(db) {
              db.User.hasMany(db.Comment, { foreignKey: "commenter", sourceKey: "id" });
          }
      cs
    • comment.js
      1
      2
      3
          static associate(db) {
              db.Comment.belongsTo(db.User, { foreignKey: "commenter", targetKey: "id" });
          }
      cs

1:1

  • hasOne

    • hasMany 메서드 대신 hasOne 메서드를 사용합니다.

    • Info: 사용자 정보를 담고 있는 가상의 모델이 있다고 가정합니다.

  • 코드

    • info.js

      1
      2
      3
          static associate(db) {
              dbInfo.belongsTo(db.User, { foreignKey: "UserId", targetKey: "id" });
          }
      cs
    • user.js

      1
      2
      3
          static associate(db) {
              db.User.hasOne(db.Info, { foreignKey: "UserId", sourceKey: "id" });
          }
      cs

N:M

  • N:M의 예시로는 게시글과 해시태그의 관계가 있습니다.

  • 게시글 하나에 태그를 여러개 가질 수 있습니다.

  • 태그 하나에 게시글이 여러개 있을 수 있습니다.

  • 시퀄라이즈에는 N:M 관계를 표현하기 위한 belongsToMany 메서드가 있습니다.

  • 코드

    • post.js

      1
      2
      3
          static associate(db) {
              db.Post.belongsToMany(db.Hashtag, { through: "PostHashtag" });
          }
      cs
    • hashtag.js

      1
      2
      3
          static associate(db) {
              db.Hashtag.belongsToMany(db.Post, { through: "PostHashtag" });
          }
      cs

0개의 댓글