sequelize M:N 관계 설정

sangeun jo·2022년 3월 13일
0

User, Project라는 모델이있고, M:N 관계이다.

이때 sequelize에서 관계설정하는 법

User.js

const Sequelize = require('sequelize');

module.exports = class Project extends Sequelize.Model {
	static init(sequelize) {
		return super.init({
			proj_no: {
				type: Sequelize.INTEGER,
                primaryKey: true,
				allowNull: false,
				unique: true
			},
			proj_name: {
				type: Sequelize.STRING(100),
				allowNull: false,
				unique: false
			},
			proj_startdate: {
				type: Sequelize.STRING(20),
				allowNull: false,
				unique: true
			},
            proj_enddate: {
				type: Sequelize.DATE,
				allowNull: false,
				unique: false
			}
		},
		{
			sequelize,
			timestamps: false,
			underscored: false,
			modelName: 'Project',
			tableName: 'project',
			paranoid: false,
			charset: 'utf8mb4',
			collate: 'utf8mb4_general_ci'
		}); 
	}

    static associate(db) {
        db.User.belongsToMany(db.Project, {
            through: 'user_project' //user_project 테이블 따로 안만들어도 됨. 자동으로 만들어짐
        });
    }
};

Project.js

const Sequelize = require('sequelize');

module.exports = class User extends Sequelize.Model {
	static init(sequelize) {
		return super.init({
			usr_email: {
				type: Sequelize.STRING(50),
                primaryKey: true,
				allowNull: false,
				unique: true
			},
			usr_password: {
				type: Sequelize.STRING(60),
				allowNull: false,
				unique: false
			},
			usr_name: {
				type: Sequelize.STRING(20),
				allowNull: false,
				unique: true
			},
            created_at: {
				type: Sequelize.DATE,
				allowNull: false,
				unique: false
			},
            change_pass: {
				type: Sequelize.DATE,
				allowNull: true,
				unique: false
			},
			is_super: {
				type: Sequelize.CHAR(1), 
				unique: false,
				defaultValue: 'N' 
			}, 
            activate_yn: {
				type: Sequelize.CHAR(1),
				allowNull: true,
				unique: false,
                defaultValue: 'Y'
			},
		},
		{
			sequelize,
			timestamps: false,
			underscored: false,
			modelName: 'User',
			tableName: 'user',
			paranoid: false,
			charset: 'utf8mb4',
			collate: 'utf8mb4_general_ci'
		});
	}

	static associate(db) {
        db.Project.belongsToMany(db.User, {
            through: 'user_project' //user_project 테이블 따로 안만들어도 됨. 자동으로 만들어짐
        });
    }

};

index.js

const Sequelize = require('sequelize');

const User = require('./User');
const Project = require('./Project');

const env = process.env.NODE_ENV || 'development';
const config = require('../config/dbconfig')[env];

const db = {};

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

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

db.User = User;
db.Project = Project; 

User.init(sequelize);
Project.init(sequelize);

User.associate(db);
Project.associate(db);

module.exports = db;

마이그레이션 등 복잡한 과정 없이 몇 줄만 추가하면 된다.

profile
코더가 아니라 개발자가 되자

0개의 댓글