본문 바로가기
Node.js

데이터베이스 - Sequelize 쿼리 정리

by Programmer.Junny 2025. 1. 17.

1. 테이블 생성

1.1. MySQL

/* MySQL */
CREATE TABLE nodejs.user (
    -> id INT NOT NULL AUTO_INCREMENT,
    -> name VARCHAR(20) NOT NULL,
    -> married TINYINT NOT NULL,
    -> comment TEXT NULL,
    -> created_at DATETIME NOT NULL DEFAULT now(),
    -> PRIMARY KEY(id),
    -> UNIQUE INDEX name_UNIQUE (name ASC))
    -> COMMENT = '사용자 정보'
    -> DEFAULT CHARACTER SET = utf8
    -> ENGINE = InnoDB;

 

1.2. Sequelize

/* Sequelize */
const Sequelize = require('sequelize');

class Comment extends Sequelize.Model {
  static initiate(sequelize) {
    Comment.init({
      comment: {
        type: Sequelize.STRING(100),
        allowNull: false,
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: true,
        defaultValue: Sequelize.NOW,
      },
    }, {
      sequelize,
      timestamps: false,
      modelName: 'Comment',
      tableName: 'comments',
      paranoid: false,
      charset: 'utf8mb4',
      collate: 'utf8mb4_general_ci',
    });
  }

  static associate(db) {
    db.Comment.belongsTo(db.User, { foreignKey: 'commenter', targetKey: 'id' });
  }
};

module.exports = Comment;

테이블 정의

/* Sequelize */
const User = require('./user');

const config = require('../config/config')[env];
const db = {};

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

db.sequelize = sequelize;

db.User = User;

User.initiate(sequelize);
User.associate(db);

테이블 생성

2. CREATE (데이터 삽입)

2.1. MySQL

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

2.2. Sequelize

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

3. READ (데이터 조회)

3.1. 모든 데이터 조회

3.1.1. MySQL

SELECT * FROM nodejs.users;

3.1.2. Sequelize

User.findAll({});

3.2. 하나의 데이터 조회

3.2.1. MySQL

SELECT * FROM nodejs.users LIMIT 1;

3.2.2. Sequelize

User.findOne({});

3.3. 특정 컬럼만 조회

3.3.1. MySQL

SELECT name, married FROM nodejs.users;

3.3.2. Sequelize

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

3.4. 조건부 조회 (WHERE AND)

3.4.1. MySQL

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

3.4.2. Sequelize

const { Op } = require('sequelize');
User.findAll({
  attributes: ['name', 'age'],
  where: {
    married: true,
    age: { [Op.gt]: 30 },
  },
});

3.5. 조건부 조회 (WHERE OR)

3.5.1. MySQL

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

3.5.2. Sequelize

User.findAll({
  attributes: ['id', 'name'],
  where: {
    [Op.or]: [
      { married: false },
      { age: { [Op.gt]: 30 } }
    ],
  },
});

3.6. 정렬

3.6.1. MySQL

SELECT id, name FROM users ORDER BY age DESC;

3.6.2. Sequelize

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

3.7. LIMIT과 OFFSET

3.7.1. MySQL

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

3.7.2. Sequelize

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

4. UPDATE (데이터 수정)

4.1. MySQL

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

4.2. Sequelize

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

5. DELETE (데이터 삭제)

5.1. MySQL

DELETE FROM nodejs.users WHERE id = 2;

5.2. Sequelize

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

6. Sequelize 관계형 쿼리

6.1. 조회

6.1.1. Include로 관계 조회

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

6.1.2. get메서드로 관계 조회

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

6.2. 관계 추가

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

6.3. 다중 관계 추가

const user = await User.findOne({});
const comment1 = await Comment.create();
const comment2 = await Comment.create();
await user.addComment([comment1, comment2]);

6.4. as 옵션 사용

  • as 옵션을 사용하여 관계된 모델의 이름을 변경
// 관계 설정
db.User.hasMany(db.Comment, {
  foreignKey: 'commenter',
  sourceKey: 'id',
  as: 'Answers'
});

// 쿼리
const user = await User.findOne({});
const comments = await user.getAnswers();

6.5. 조건부 관계 조회

6.5.1. Include로 관계 조회

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

6.5.2. get메서드로 관계 조회

const comments = await user.getComments({
  where: { id: 1 },
  attributes: ['id'],
});

7. Op 연산자 종류

  • Op.gt: 초과
  • Op.gte: 이상
  • Op.lt: 미만
  • Op.lte: 이하
  • Op.ne: 같지 않음
  • Op.or: OR 연산
  • Op.in: 배열 요소 중 하나
  • Op.notIn: 배열 요소와 모두 다름

최근댓글

최근글

skin by © 2024 ttuttak