교육
[Node.js] 4일차
사람냄새나는 개발자
2019. 9. 11. 01:46
수업 내용 정리
- ORM
- 모델 간의 관계
ORM (Object Relational Mapping)
- 객체 지향 프로그래밍 언어와 관계형 DB 간의 매핑을 지원하는 프로그래밍 기술
- Object-relational mapping (ORM) in computer science is a programming technique for converting data.........~
- 객체와 관계형 DB의 테이블 간에 불일치를 해결해줌 (중간 다리 역할)
Sequelize
- 프로미스 기반 Node.js ORM 라이브러리
- Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server.
모델 관계 설정
- associate안에 적어줌
let Products = sequelize.define('Products', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
name: {type: DataTypes.STRING},
thumbnail: {type: DataTypes.STRING},
price: {type: DataTypes.INTEGER},
description: {type: DataTypes.TEXT}
}, { // 옵션 설정
timestamps: true,
underscored: true
});
// Product 모델 관계도
Products.associate = (models) => {
// Memo 모델에 외부키를 둠
// onDelete 옵션이 'CASCADE'인 경우 제품이 삭제되면 자신의 메모들도 전부 삭제됨
Products.hasMany(models.ProductsMemo, {
// as에 따라 함수명이 변경됨 (as 중요함)
as: 'Memo',
foreignKey: 'product_id',
sourceKey: 'id',
onDelete: 'CASCADE'
});
Products.belongsTo(models.User, {
as: 'Owner',
foreignKey: 'user_id',
targetKey: 'id'
});
};
참고