본문 바로가기

JavaScript/Express.js

[Express.js] 테이블간 관계 정의 (User - Board)

1. 테이블간 관계

User - Board 관계

 

2. Board.js 작성

      - board 테이블에 해당하는 Board model 작성
      - 1:N 관계중 N이기 때문에 belongsTo 사용

// models/board.js

const Sequelize = require("sequelize");

module.exports = class Board extends Sequelize.Model {
  static init(sequelize) {
    return super.init(
      {
        title: {
          type: Sequelize.STRING(40),
          allowNull: false,
        },
        content: {
          type: Sequelize.TEXT,
          allowNull: false,
        },
      },
      {
        sequelize,
        charset: "utf8",
        collate: "utf8_general_ci",
        tableName: "board",
        modelName: "Board",
        underscored: true,
        timestamps: false,
      }
    );
  }
  // ** 테이블간 관계 정의
  static associate(db) {
    db.Board.belongsTo(db.User, { foreignKey: "user_id", targetKey: "id" });
  }
};

 

3. User.js 수정

      - Board와의 관계 정의를 위해 associate 메서드 작성
      - 1:N 관계중 1이기 때문에 hasMany 사용

// models/user.js

const Sequelize = require("sequelize");

module.exports = class User extends Sequelize.Model {
  static init(sequelize) {
    return super.init(
      {
        username: {
          type: Sequelize.STRING(40),
          allowNull: false,
        },
        password: {
          type: Sequelize.STRING(40),
          allowNull: false,
        },
        name: {
          type: Sequelize.STRING(20),
          allowNull: false,
        },
      },
      {
        sequelize,
        charset: "utf8",
        collate: "utf8_general_ci",
        tableName: "user",
        modelName: "User",
        underscored: true,
        timestamps: false,
      }
    );
  }
  // ** 테이블간 관계 정의
  static associate(db) {
    db.User.hasMany(db.Board, { foreignKey: "user_id", sourceKey: "id" });
  }
};

 

4. Index.js 수정

      - 각 모델을 db객체에 추가

      - 각 모델의 init, associate 메서드 호출

// models/index.js

const Sequelize = require("sequelize");
const User = require("./user");
const Board = require("./board");

const env = "development";
const config = require("../config/config")[env];
const db = {};

const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  config
);

db.sequelize = sequelize;

// ** db 객체에 User Model 담기
db.User = User;
db.Board = Board;

// ** User init 메서드 호출
User.init(sequelize);
Board.init(sequelize);

// ** 관계 설정
User.associate(db);
Board.associate(db);

module.exports = db;

 

5. 서버 실행

      - 아래의 로그 중 ' CREATE TABLE IF NOT EXISTS `board` ' 부분이 출력됨
      - 데이터베이스를 확인했을 때 board 테이블이 아래와 같이 구성됨

$ npm start

...
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'user' AND TABLE_SCHEMA = 'node_study'
Executing (default): SHOW INDEX FROM `user` FROM `node_study`
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'board' AND TABLE_SCHEMA = 'node_study'
Executing (default): CREATE TABLE IF NOT EXISTS `board` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(40) NOT NULL, `content` TEXT NOT NULL, `user_id` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
Executing (default): SHOW INDEX FROM `board` FROM `node_study`
DB 연결 성공

board 테이블 구조

 

 

github: https://github.com/DongyangOne/one-node-study/tree/master/table_relationship_setting