MySQL (sequelize) 쿼리 생성(요약)

parkjh9370·2022년 2월 19일
0

시퀄라이즈 라이브러리 - MySQL 연결 및 요청

  1. 설치
npm i sequelize sequelize-cli mysql2
  1. 시퀄라이즈 구조 생성
npx sequelize init
  1. DB 테이블 생성
npx sequelize db:create

🔥 데이터 추가

INSERT INTO nodejs.users (name, age, married, comment) VALUES ('zero', 24, 0, '자기소개1');

const { User } = require('../models');
User.create({
  name: 'zero',
  age: 24,
  married: false,
  comment: '자기소개1',
}

🔥 데이터 조회

👉 모든 데이터 조회

SELECT * FROM nodejs.users;

User.findAll({});

👉 데이터 1개만 가져오기

SELECT * FROM nodejs.users LIMIT 1;

User.findOne({});

👉 원하는 컬럼만 가져오기(attributes 옵션)

SELECT name, married FROM nodejs.users;

User.findAll({
	attributes: ['name', 'married'],
});

👉 조건들을 나열하기(WHERE, [Op.gt])

SELECT name, age FROM nodejs.users WHERE married = 1 AND age >30;

const { Op } = require('sequelize');
const { User } = require('../models);
User.findAll({
  attributes: ['name', 'age'],
  where: {
    married: true,
    age: { [Op.gt]: 30},
  },
});
  • Op.gt: 초과
  • Op.gte: 이상
  • Op.lt: 미만
  • Op.lte: 이하
  • Op.ne: 같지않음
  • Op.or: 또는
  • Op.in: 배열 요소 중 하나
  • Op.notIn: 배열 요소와 모두 다름

👉 조건들을 나열하기(WHERE, [Op.or])

SELECT id, name FROM users WHERE married = 0 OR age > 30;

const { Op } = require('sequelize');
const { User } = require('../models);
User.findAll({
  attributes: ['id', 'name'],
  where: {
    [Op.or]: [{ married: false}, { age: { [Op.get]: 30 } }],
  },
});

👉 정렬하기

SELECT id, name FROM users OREDER BY age DESC;

User.findAll({
  attributes: ['id', 'name'],
  order: [['age', 'DESC']],
});

👉 조회할 row(->) 개수 설정 ( limit )

SELECT id, name FROM users OREDER BY age DESC LIMIT 1;

User.findAll({
  attributes: ['id', 'name'],
  order: [['age', 'DESC']],
  limit: 1,
});

👉 조회할 row(->) 개수 설정 ( limit, offset )

SELECT id, name FROM users OREDER BY age DESC LIMIT 1 OFFSET 1;

User.findAll({
  attributes: ['id', 'name'],
  order: [['age', 'DESC']],
  limit: 1,
  offset: 1,
});

🔥 데이터 수정

UPDATE nodejs.users SET comment = '바꿀 내용' WHERE id = 2;

User.update({
  comment: '바꿀 내용',
}, {
  where: { id: 2 },
});

🔥 데이터 삭제

DELETE FROM nodejs.users WHERE id = 2;

User.destroy({
  where: { id: 2 }
});

🔥 관계 쿼리

👉 findOne, findAll 메서드를 호출할 때 프로미스의 결과로 모델을 반환
(findAll의 경우 모두 찾는 것이므로 모델의 배열을 반환)

	const user = await User.findOne({});
	console.log(user.nick) // 사용자 닉네임

👉 include - 관계 커리 기능 지원 (MYSQL의 JOIN)

	const user = await User.findOne({
      include: [{
        model: Comment,
      }]
    });
	console.log(user.Comments); // 사용자 댓글

혹은, 이와 같은 형태로도 댓글에 접근 가능

	const user = await User.findOne({});
	const comments = await.user.getComments();
	console.log(comments); // 사용자 댓글

관계를 설정했다면

  • getComments(조회), setComments(수정), addComment(하나 생성), addComments(여러 개 생성), removeComments(삭제) 메서드를 지원

동사 뒤의 모델을 바꾸고 싶다면 관계 설정 시 as 옵션 사용

	// 관계 설정 시 as로 등록
	db.User.hasMany(db.Comment, 
           { foreignKey: 'commenter', sourceKey: 'id, as:'Answers'});
	// 쿼리 할 때는        
    const user = await User.findOne({});
	const comments = await user.getAnswers();
	console.log(comments); // 사용자 댓글

as 설정 시 include 시 추가 되는 댓글 객체도 user.Answers 로 바뀜

(include, 관계 커리 메서드에서도 where, attributes 옵션 사용 가능)

👉 댓글 가져올 때 id가 1인 댓글만 가져오고, 컬럼도 id 컬럼만 가지고 오고 싶을 때

	const user = await User.findOne({
      include: [{
        model: Comment,
        where: {
          id: 1,
        },
        attributes: ['id'],
      }]
    });
//또는
	const comments = await user.getComments({
      where: {
        id: 1,
      },
      attributes: ['id'],
    });

관계 쿼리일 때 조회와 다르게 수정, 생성, 삭제 는 조금 다르게 쿼리

	const user = await User.findOne({});
	const comment = await Comment.create();
	await user.addComment(comment);
	//또는
	await user.addComment(comment.id);

🔥 SQL 쿼리하기

👉 시퀄라이즈에서 직접 SQL문 사용하기

	const [result, metadata] = await sequelize.query('SELECT * from comments');
	console.log(result);

출처: Node.js 교과서(길벗)

주의 사항

주의해야 할 점으로 환경변수 모듈을 사용하기 위해 config.json을 config.js로 변경하였는데, 확장자가 js로 변경됨으로써 생성된 model들을 처리를 담당하는 ./models/index.js가 config.js의 설정을 읽지 못하게 되는 문제가 발생한다.

따라서 아래와 같이 코드를 다듬어 줄 필요가 있다.

./models/index.js

 변경 전
const config = require(__dirname + '/../config/config.json')[env];

 변경 후
const config = require(`${__dirname}/../config/config.js`)[env];

참조: https://sequelize.org/master/manual/migrations.html

0개의 댓글