> For the complete documentation index, see [llms.txt](https://adam-37.gitbook.io/joomadeung/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adam-37.gitbook.io/joomadeung/node.js/node.js-express-mysql/sequelize-mysql.md).

# Sequelize를 사용해 MySQL와 연결

### Sequelize 모델

#### 1. 유저 sequelize

user.js

```jsx
const Sequelize = require('sequelize');

// class <모델 이름>
class User extends Sequelize.Model {
  static initiate(sequelize) {
    User.init(
      // 첫 번째 매개변수: 모델의 옵션을 정의하는 객체
      {
        // sequelize는 id를 자동으로 넣어주기 때문에 생략 가능
        // id: {
        //   type: Sequelize.INTEGER,
        //   primaryKey: true,
        //   autoIncrement: true,
        // },
        name: {
          type: Sequelize.STRING(20), // VARCHAR
          allowNull: false, // not null
          unique: true, // 고유값
        },
        age: {
          type: Sequelize.INTEGER.UNSIGNED,
          allowNull: false,
        },
        married: {
          type: Sequelize.BOOLEAN, // TINYINT(1)
          allowNull: false,
        },
        comment: {
          type: Sequelize.TEXT, // TEXT
          allowNull: true,
        },
        created_at: {
          type: Sequelize.DATE, // DATETIME, MySQL: DATE = Sequelize: DateOnly
          allowNull: false,
          defaultValue: Sequelize.NOW, // now()
        },
        // createdAt, updatedAt, deletedAt: true(soft delete)
      },
      {
        // 두 번째 매개변수: 모델의 옵션을 정의하는 객체
        sequelize,
        timestamps: false, // true면 createdAt, updatedAt을 넣어줌
        underscored: false,
        modelName: 'User',
        tableName: 'users',
        paranoid: false, // true면 제거한 날짜도 만들어짐
        charset: 'utf8',
        collate: 'utf8_general_ci',
      }
    );
  }

  static associate(db) {
    // 다른 모델과의 관계를 정의하는 데 사용
		// Comment의 Commenter라는 칼럼이 내 id를 참고하고 있다.
    db.User.hasMany(db.Comment, { foreignKey: 'commenter', sourceKey: 'id' });
  }
}

module.exports = User;
```

#### 2. 댓글 squelize

comment.js

```jsx
const Sequelize = require('sequelize');

class Comment extends Sequelize.Model {
  static initiate(sequelize) {
    Comment.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' }); // Comment 모델이 User 모델의 commenter(댓글 작성자)와 관련이 있다는 것을 명시적으로 나타내기 위함
  }
}

module.exports = Comment;
```

* `belongsTo()` 메서드에서 `targetKey`옵션을, `hasMany()`메서드에서 `sourceKey` 옵션을 주로 사용

### MySQL, Sequelize 데이터 유형 비교

| MySQL 데이터 유형 | Sequelize 데이터 유형 |
| ------------ | ---------------- |
| INT          | INTEGER          |
| BIGINT       | BIGINT           |
| FLOAT        | FLOAT            |
| DOUBLE       | DOUBLE           |
| DECIMAL      | DECIMAL          |
| CHAR         | CHAR             |
| VARCHAR      | STRING           |
| TINYTEXT     | TEXT             |
| TEXT         | TEXT             |
| MEDIUMTEXT   | TEXT             |
| LONGTEXT     | TEXT             |
| DATE         | DATE             |
| TIME         | TIME             |
| DATETIME     | DATE             |
| TIMESTAMP    | DATE             |
| YEAR         | INTEGER          |
| BLOB         | BLOB             |
| TINYBLOB     | BLOB             |
| MEDIUMBLOB   | BLOB             |
| LONGBLOB     | BLOB             |
| BOOLEAN      | BOOLEAN          |
