sequelize foreign key 생성하기

정창민·2022년 12월 23일
0

https://loy124.tistory.com/374 <= 블로그를 참고하였음



1. models, migration 생성하기

1-1

npx sequelize model:generate --name User --attributes nickname:string,password:string,confirm:string

npx sequelize model:generate --name Post --attributes title:string,content:string
  • models 폴더에 user, post.js
  • migration 폴더에 20221221082407-create-user, post.js 생성


1-2

 npx sequelize db:migrate
  • db에 테이블 생성


1-3

npx sequelize migration:generate --name fk-comment
  • 생성 된 20221223053004-fk-post 파일 확인
'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {
    await queryInterface.addColumn('Posts', 'user_id', {
      type : Sequelize.INTEGER,
      allowNull: false
    })
    await queryInterface.addConstraint('Posts', {
      fields : ['user_id'],
      type : 'foreign key',
      name : 'users_posts_id_fk',
      references : {
        table : 'Users',
        field : 'userId'
      },
      onDelete : 'cascade',
      onUpdate : 'cascade'
    })
  },
  async down (queryInterface, Sequelize) {
    await queryInterface.removeColumn('Posts', 'user_id')
  }
};
  • 코드를 추가 후 npx sequelize db:migrate 테이블 적용!



2. model 매핑하기

2-1. models/user.js

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * 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) {
      // define association here
      models.User.hasMany(models.Post, {foreignKey : 'user_id'})
    }
  }
  User.init({
    userId : {
      primaryKey : true,
      type : DataTypes.INTEGER
    },
    nickname: DataTypes.STRING,
    password: DataTypes.STRING,
    confirm: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};


2-2. models/post.js

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Post extends Model {
    /**
     * 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) {
      // define association here
      models.Post.belongsTo(models.User, {foreignKey : 'user_id'})
    }
  }
  Post.init({
    postId : {
      primaryKey : true,
      type : DataTypes.INTEGER
    },
    title: DataTypes.STRING,
    content: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Post',
  });
  return Post;
};
  • post는 user에 종속 됨
  • 매핑 완료


3. 게시글 작성 시 user_id 넣어주기

3-1. 로그인 검증 미들웨어

const jwt = require('jsonwebtoken')
const {User} = require('../models')

module.exports = async (req, res, next) => {
  const { authorization } = req.headers;
  const [authType, authToken] = (authorization || "").split(" ");

  if(authType !== 'Bearer' || !authToken) return res.status(400).json({errMessage : '로그인 후 사용이 가능한 API입니다.'})

  try {
    const {userId} = jwt.verify(authToken, 'my-secrect-key')
    const user = await User.findByPk(userId)
    res.locals.user = user.dataValues
    console.log(res.locals.user)
    next()

  } catch (err) {
    return res.status(500).json({errorMessage : err})
  }
}



3-2. 게시글 작성 라우츠 폴더

const express = require('express')
const router = express.Router()

const {Post} = require('../models')
const authMiddleware = require('../middlewares/auth-middleware.js')

// 게시글 작성
router.post('/posts', authMiddleware, async (req, res) => {
  const {title , content} = req.body
  const currentUser = res.locals.user

  if(!title || !content) return res.status(400).json({errMessage : '값을 입력해주세요'})

  try {
    if(currentUser) {
      await Post.create({title : title, content : content, user_id : currentUser.userId})
      res.status(201).json({message : '게시글 작성에 성공하였습니다.'})
    }
  } catch (err) {
    res.status(500).json({errorMessage : err})
  }
})


module.exports = router
  • create 시 table의 user_id 컬럼에 currentUser.userId 입력!!!
profile
안녕하세요~!

0개의 댓글