본문 바로가기
깃허브 링크!
node.js프로젝트(김아현,이무헌,박민우,신근호)

sequelize사용 팀프로젝트 -1day (hasmany belongsTo )

오늘은 sequelize 사용해서

class가 reserved list / chatlogs / theaters를 만들어 보았다. 

 

⁕chatLogs

Table chatLogs{
  id integer [primary key]

  user_id integer [ref: > users.id]
  content text

  created_at timestamp
}
const Sequelize = require("sequelize");
class ChatLog extends Sequelize.Model {
    static init(sequelize){
        return super.init({
            
            
        content : {
            type : Sequelize.TEXT,
            allowNull : false,
        },




        },{
            // 테이블의 내용
            sequelize, 
            timestamps : true, // 생성 시간, 업데이트 시간 자동으로 생성
            underscored : false, // 카멜 케이스 설정 유무
            modelName : "ChatLog", //모델 이름
            tableName : "chatLogs", // 복수형으로 테이블 이름 설정
            paranoid : false, //삭제시간 생성 유무
            charset : "utf8", // 인코딩 방식은 꼭 설정 해야한다.
            collate : "utf8_general_ci",
        })
    }

   
    static associate(db){
       
        db.ChatLog.belongsTo(db.User,{foreignKey : "user_id",targetKey : "id"});
    }
}

module.exports = ChatLog;

 

 

⁕reserved list

Table reservedList{
  id integer [primary key]

  show_id integer [ref: > shows.id]
  user_id integer [ref: > users.id]
  reservation_num varchar
  // 몇행몇열인지 배열로 저장
  seat_num varchar

  created_at timestamp
}
const Sequelize = require("sequelize");
class ReservedList extends Sequelize.Model {
    static init(sequelize){
        return super.init({
            // 컬럼의 내용
           reservation_num : {type
        :Sequelize.STRING(20),allowNull:false},
            
        seat_num : {
            type : Sequelize.STRING(150),
            allowNull : false,
        },




        },{
            // 테이블의 내용
            sequelize, 
            timestamps : true, // 생성 시간, 업데이트 시간 자동으로 생성
            underscored : false, // 카멜 케이스 설정 유무
            modelName : "ReservedList", //모델 이름
            tableName : "reservedLists", // 복수형으로 테이블 이름 설정
            paranoid : false, //삭제시간 생성 유무
            charset : "utf8", // 인코딩 방식은 꼭 설정 해야한다.
            collate : "utf8_general_ci",
        })
    }

    static associate(db){
        db.ReservedList.belongsTo(db.Show, {foreignKey : "show_id", targetKey : "id"});
        db.ReservedList.belongsTo(db.User,{foreignKey : "user_id",targetKey : "id"});
    }
   
}

module.exports = ReservedList;

⁕theaters 

Table theaters{
  id integer [primary key]

  name varchar
  location varchar


  created_at timestamp
}
const Sequelize = require("sequelize");
class Theater extends Sequelize.Model {
    static init(sequelize){
        return super.init({
            
            
       name : {
        type : Sequelize.STRING(20),
        allowNull : false
       },     

       location : {
        type : Sequelize.STRING(30),
        allowNull:false
       }





        },{
            // 테이블의 내용
            sequelize, 
            timestamps : true, // 생성 시간, 업데이트 시간 자동으로 생성
            underscored : false, // 카멜 케이스 설정 유무
            modelName : "Theater", //모델 이름
            tableName : "theaters", // 복수형으로 테이블 이름 설정
            paranoid : false, //삭제시간 생성 유무
            charset : "utf8", // 인코딩 방식은 꼭 설정 해야한다.
            collate : "utf8_general_ci",
        })
    }

   
    static associate(db){
       
        db.Theater.hasMany(db.Show,{foreignKey : "theaters_id",targetKey : "id"});
    }
}

module.exports = Theater;

sequelize는 node.js에서 객체 관계 매핑(orm) 라이브러리로, 데이터베이스와 상호 작용하는 간단한 방법을 제공한다.
chatlog 클래스의 init() 메서드는 모델의 구조와 옵션을 정의하는데 사용된다.

init 메서드의 첫번째 인자는 테이블의 컬럼을 정의하는 객체이다.(속성의 값은 데이터 타입, 제약조건등이 있다.)
두번째 인자는 테이블의 옵션을 정의하는 객체(테이블의 이름, 생성시간 등등)

sequelize는 기본적으로 id 라는 이름의 정수 기본 키를 자동으로 생성한다.
따라서 코드에서 id 컬럼을 정의하지 않아도 id 컬럼이 자동으로 생성되고 기본키로 사용된다.

따라서 user_id 컬럼과 같이 외래 키(foreign key)를 정의할 때는 id 컬럼의 자동 생성을 이용하여 다른 테이블과의 관계를 설정할수 있다.
belongsTo() 메서드에서 foreingKey와 targetKey 옵션을 사용하여 user_id 컬럼과 User 모델의 id 컬럼간의 관계를 정의하고 있다.

 

 

hasmany와 belongs to

1. theater 모델에서의 hasMany 관계
static associate(db) {
  db.Theater.hasMany(db.Show, { foreignKey: "theaters_id", targetKey: "id" });
}​
hasmany는 "한 개의 theater는 여러 개의 show를 가질수 있다는 관계를 정의한다.
theater 모델의 theaters_id 컬럼과 show 모델의 id 컬럼을 왜래키로 사용하여 연결한다.

2.ChatLog 모델에서의 belongsTo 관계
static associate(db) {
  db.ChatLog.belongsTo(db.User, { foreignKey: "user_id", targetKey: "id" });
}​

belongsTo 는 한 개의 ChatLog는 하나의 User에 속할 수 있다는 관계를 정의
ChatLog 모델의 user_id 컬럼과 User모델의 id 컬럼을 왜래키로 사용하여 연결한다.