프로젝트

[프로젝트] 다대다 관계 N:M Sequalize

이채야채 2022. 1. 18. 13:37

1.npm install --save-dev sequelize-cli

2.npx sequelize-cli init

3.Database만들기

4.config.json 수정

5.스키마 추가 npx sequelize-cli model:generate --name url --attributes url: 'STRING', title: 'STRING', visits: 'INTEGER' (카멜표기법 필수)

6.npx sequelize-cli db:migrate

7.모델스 수정

   -7-1 다의 관계 수정 users.hasMany(models.contents);

   -7-2 1의 관계 수정 contents.belongsTo(models.users, { foreignKey: "userId" });

8. 조인 할때 쓰는 코드 const userInfo = await model.users.findOne({ include: { model: model.contents, where: { userId: 1 }, }, });

 

 ✔️ 조인테이블은 자동생성되는 원리. 개발자가 직접 만들어주는것이아니다.

 

App.js

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
// const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize = new Sequelize('practice', 'root', '1234', 
  {
    host: 'localhost',
    dialect: 'mysql',
    logging: console.log
  }
);

fs
  .readdirSync(__dirname + '/models')
  .filter(file => {
    console.log(file);
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname + '/models', file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;


/**  
 * join table 에 테이블에 데이터 자동 저장예제 (이후 eager loading 사용 가능)
* 참조: 
* - https://sequelize.org/v7/manual/assocs.html#many-to-many-relationships
* - https://sequelize.org/v7/manual/eager-loading.html
*/

db.sequelize.sync();
console.log("models synchronization complete!");

const Hash = db["hash"];
const Post = db["post"];

(async () => {
  // DB 에 데이터 저장하는 insert 명령 추상화 된거 SQL insert 에 해당.
  let h1 = await Hash.create({content: "hash1"});
  // DB 에 데이터 저장하는 insert 명령 추상화 된거 SQL insert 에 해당.
  let p1 = await Post.create({visit: "post1"})
  await h1.addPost(p1);
  let h2 = await Hash.create({content: "hash2"});
  await h2.addPost(p1);

  let all = await Hash.findAll({include: [{model: Post}]});
  console.log("hash posts ", all[all.length - 1].dataValues.posts);
})();

module.exports = db;

hash.js

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class hash 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
      hash.belongsToMany(models.post, {
        through: "hashPost",
        foreignKey: "hashId",
      });
    }
  }
  hash.init(
    {
      content: DataTypes.STRING,
    },
    {
      sequelize,
      modelName: "hash",
    }
  );
  return hash;
};

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
      post.belongsToMany(models.hash, {
        through: "hashPost",
        foreignKey: "postId",
      });
    }
  }
  post.init(
    {
      visit: DataTypes.STRING,
    },
    {
      sequelize,
      modelName: "post",
    }
  );
  return post;
};