sprint
Repository: im-sprint-shortly-mvc
- sequelize-cli를 이용해 mvc pattern을 구현하는 법
npx sequelize-cli init- 기본 세팅을 진행, 아래와 같은 폴더들이 생성됨
config: DB와 연결하는 정보를 담은 폴더. sprint에서는.json으로 되어있으나
js파일로dotenv모듈을 이용해 환경변수를 불러와 연결하는 것도 가능models: 필요한 model을 생성해 관리하는 폴더migrations: 스키마의 테이블 필드의 타입 정보가 담겨 있는 파일로 구성(db:migrate및undo명령어 시 호출되는 up, down method 포함,queryInterfaceAPI 참조)seeders: 필드에 맞는 데이터를 레코드로 삽입할 수 있는 파일로 구성
npx sequelize-cli model:generate --name [name] --attributes [field][dataType]- 주어진 명령어대로 model 생성 및
XXXXXXXXXXXXXX-create-[name].js과 같은 migration 파일 생성
npx sequelize-cli db:migrate- dataType 설정에 맞춘 Field를 생성해주는 명령어
- (optional)
npx sequelize-cli seed:generate --name,db:seed:all - bulk insert할 seed 파일 존재 시 레코드 삽입
- (optional)
- Migration Skeleton 형식
1 2 3 4 5 6 7 8
module.exports = { up: (queryInterface, Sequelize) => { // db:migrate }, down: (queryInterface, Sequelize) => { // db:migrate:undo } }
- model 형식
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
'use strict'; const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) => { class user extends Model { // Model Class를 확장하여 sequelize query method 사용 /** * Helper method for defining associations. * This method is not a part of Sequelize lifecycle. * The `models/index` file will call this method automatically. */ static associate(models) { // 참조하는 다른 model(table)과의 관계 설정 / hasOne, hasMany, belongsTo this.hasMany(models.url) } } user.init({ name: DataTypes.STRING }, { sequelize, modelName: 'user', }); return user; };
Associations을 이용한 Join Table 구현
- 모델 생성 cli 이용해서 user 모델 생성
- 해당하는 model 폴더 내의 파일에 관계 설정을 해줍니다.
- url파일에서도 user와 관계 설정
- user와 url에서도 관계 설정
- 마이그레이션 파일을 작성해야하는데
- skeleton 비어있는 템플릿 파일 생성하는 cli 명령어
- 공식문서 참조해서 queryInterface 메소드를 이용해서
- userId 컬럼 생성
- userId 컬럼에 FK 제약 생성
- 마이그레이션 → 두개의 파일이 마이그레이션 됨 (1. user테이블 생성, 2. userId FK 생성)