시퀄라이즈(2)

올챙이·2024년 9월 2일

Node.js

목록 보기
20/23
post-thumbnail

시퀄라이즈 사용하기

모델 정의하기

  • MySQL에서 정의한 테이블을 시퀄라이즈에서도 정의해야 합니다.

  • 시퀄라이즈는 모델과 MySQL의 테이블을 연결해주는 역할을 합니다.

  • models/user.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    const Sequelize = require("sequelize");
     
    class User extends Sequelize.Model {
        static initiate(sequelize) {
            User.init(
                {
                    name: {
                        type: Sequelize.STRING(20),
                        allowNull: false,
                        unique: true,
                    },
                    age: {
                        type: Sequelize.INTEGER.UNSIGNED,
                        allowNull: false,
                    },
                    married: {
                        type: Sequelize.BOOLEAN,
                        allowNull: true,
                    },
                    created_at: {
                        type: Sequelize.DATE,
                        allowNull: false,
                        defaultValue: Sequelize.NOW,
                    },
                },
                {
                    sequelize,
                    timestamps: false,
                    underscored: false,
                    modelName: "User",
                    tableName: "users",
                    paranoid: false,
                    charset: "utf8",
                    collate: "utf8_general_ci",
                }
            );
        }
        static associate(db) {}
    }
     
    module.exports = User;
    cs
    • 두번째 인수는 테이블 옵션입니다.

    • sequelize

      • static initiate 메서드의 매개변수와 연결되는 옵션입니다.

      • db.sequelize 객체를 넣어야 합니다.

    • timestamps

      • true일 때, 열이 생성될 때와 수정될 때의 시작이 자동으로 입력됩니다.

      • 현재 created_at 컬럼을 만들었기 때문에 false로 해줍니다.

    • underscored

      • 모델과 데이터베이스 테이블의 이름에 대해 밑줄 구분 방식이 아닌 카멜 케이스를 사용합니다.
    • tableName

      • 데이터베이스의 테이블 이름이 됩니다.
    • paranoid

      • 삭제된 데이터를 실제로 제거하지 않고 상태를 변경해줍니다.

      • 복원하기 위해서사용합니다.

    • static associate(db) {}

      • 다른 모델과의 관계를 정의합니다.
  • models/comment.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    const Sequelize = require("sequelize");
     
    class Comment extends Sequelize.Model {
        static initiate(sequelize) {
            User.init(
                {
                    comment: {
                        type: Sequelize.STRING(100),
                        allowNull: false,
                    },
                    created_at: {
                        type: Sequelize.DATE,
                        allowNull: true,
                        defaultValue: Sequelize.NOW,
                    },
                },
                {
                    sequelize,
                    timestamps: false,
                    modelName: "Comment",
                    tableName: "comments",
                    paranoid: false,
                    charset: "utf8mb4",
                    collate: "utf8mb4_general_ci",
                }
            );
        }
        static associate(db) {
            db.Comment.belongsTo(db.User, { foreignKey: "commenter", targetKey: "id" });
        }
    }
     
    module.exports = Comment;
    cs
    • static associate(db) {}

      • User 모델과의 관계를 정의합니다.

      • 외래키(foreignKey)로 commenter라는 필드를 사용합니다.

      • targetKey는 id 입니다.

  • index.js 수정

    모델과 index.js와 연결합니다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    const Sequelize = require("sequelize");
    const User = require("/user");
    const Comment = require("/comment");
     
    const env = process.env.NODE_ENV || "development";
    const config = require(__dirname + "/../config/config.json")[env];
    const db = {};
     
    const sequelize = new Sequelize(config.database, config.username, config.password, config);
     
    db.sequelize = sequelize;
     
    db.User = User;
    db.Comment = Comment;
     
    User.initiate(sequelize);
    Comment.initiate(sequelize);
     
    User.associate(db);
    Comment.associate(db);
     
    module.exports = db;
    cs
    • initite
      모델의 static initiate 메서드를 호출합니다.

    • associate
      다른 테이블과의 관계를 연결해주는 메서드입니다.

0개의 댓글