시퀄라이즈 ORM(Object-relational Mapping)
시퀄라이즈 설치
npm i sequelize mysql2
npm i -g sequelize-cli
sequelize init
설치하면 config , models, migrations, seedres 폴더가 생성된다.
models/index.js 를 열고, 아래처럼 수정한다
const path = require('path');
const Sequelize = require('sequelize');
const env = process.env.NODE_ENV || 'development';
const config = require(config.database , config.username , config.password, config);
db.sequelize = sequrlize;
db.sequelize = Sequelize;
module.exports = db;
모델을 정의하는 메서드 : define('객체이름', 스키마정의, 테이블 설정)
시퀄라이즈는 id를 기본키로 연결하기 때문에 id 컬럼은 따로 적을필요가 없다
timestamps 가 true 면 createdAt , updatedAt 컬럼을 추가한다.
조인을 시퀄라이즈에서도 가능한데
1:N = hasyMany 메소드를 사용(N:1 은 belongs To)
1:1 = hasOne 사용
N : M = belongsToMany 메소드 사용
db.User.hasMany(db.Comment, { foreignKey: 'commenter', sourceKey: 'id'});
db.Comment.belongsTo(db.User, { foreignKey: 'commenter', targetKey: 'id'});
row 조회
select * from user;
User.findAll({});
select * from users limit 1;
User.find({});
select name , married from users;
User.findAll({
attributes : ['name','married']
})
select name. age from users where married =1 and age > 30;
const {User , Sequelize:{Op}} = require('../models');
User.findAll({
attrbutes : ['name', 'age'],
where : {
married : 1,
age : {[Op.gt] : 30}
}
})
Op 객체를 불러와 연산자를 활용할수 있음
Op.gt : 초과
Op.gte : 이상
Op.lt : 미만
Op.lte : 이하
Op.ne : 같지않음
Op.or : 또는
Op.in : 배열 요소중 하나
Op .notIn : 배열요소와 모두 다름
[row 수정]
User.update({
comment :'수정할내용',
},{
where: {id : 2},
});
[row 삭제]
User.delete({
where :{id : 2},
})