시퀄라이즈는 SQL문을 자바스크립트 프로젝트 내에서 자바스크립트 객체로 작성할 수 있습니다. 

그렇지만, 시퀄라이즈 자체의 SQL과 다른 문법이 존재하기 때문에 이것도 익히는데 시간이 걸릴 것 같습니다.

또한, SQL문 데이터베이스를 다룰 백엔드 개발자라면 필수로 배우고 알아둬야하기 때문에 어떤 것을 쓰는게 맞을지 모르겠습니다.

하여튼 Sequelize 문법을 알아보겠습니다. 위에 SQL을 적어 해당 SQL문이 시퀄라이즈로 작성할때 어떻게 바뀌는지 보겠습니다.

 

먼저, 가장 간단한 CRUD부터 익혀보겠습니다. 

 

1) 생성하기(INSERT) 

INSERT INTO users (name,age,married,comment) VALUES ('JANG', 24, 0, '코멘트~');

 

User.create({ // Promise 방식 

name: 'JANG',

age:24,

married: false,

comment: '코멘트~'

});

 

2) 조회하기(SELECT)

// 모든 컬럼을 전부 가지고 오기.

SELECT * FROM users;

 

User.findAll():

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

// 일부 컬럼만 전부 가지고 오기.

SELECT name, married FROM users;

 

User.findAll({

attributes: ['name','married'],

});

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

[WHERE절 추가]

 

SELECT * FROM users WHERE authorId = 2

 

User.findAll({

 where: { authorId: 2 }

});  

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

SELECT * FROM users WHERE authorId = 12 AND status = 'active';

 

User.findAll({

 where: {

  authorId: 12,

  status: 'active'

   }

});

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Op라는 연산자가 존재한다. 이것으로 조건문등의 조건을 정할 수 있다.

 

Op.eq --> SELECT * FROM users WHERE authorId = 2와 동일하다.

const { Op } = require("sequelize");
User.findAll({
  where: {
    authorId: {
      [Op.eq]: 2
    }
  }
});

Op.and --> 위 SELECT * FROM users WHERE authorId = 12 AND status = 'active'; 와 동일해짐.

const { Op } = require("sequelize");
User.findAll({
  where: {
    [Op.and]: [
      { authorId: 12 },
      { status: 'active' }
    ]
  }
});

Op.or --> SELECT * FROM users WHERE authorId = 12 OR authorId = 13; 을 표현할 수 있다.

const { Op } = require("sequelize");
User.findAll({
  where: {
    [Op.or]: [
      { authorId: 12 },
      { authorId: 13 }
    ]
  }
});

위와 같이 동일한 필드를 조건문으로 찾을 경우, 구조를 바꿔서 좀 더 읽기 쉽게 바꿀 수 있다.

 

DELETE FROM post WHERE authorId = 12 OR authorId = 13;

const { Op } = require("sequelize");
Post.destroy({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});

그 외 엄청나게 많은 종류의 연산자를 제공한다.

너무 많고해서 복붙해 넣었다. 이런게 있구나만 보고 넘어가자.

const { Op } = require("sequelize");
User.findAll({
  where: {
    [Op.and]: [{ a: 5 }, { b: 6 }],            // (a = 5) AND (b = 6)
    [Op.or]: [{ a: 5 }, { b: 6 }],             // (a = 5) OR (b = 6)
    someAttribute: {
      // Basics
      [Op.eq]: 3,                              // = 3
      [Op.ne]: 20,                             // != 20
      [Op.is]: null,                           // IS NULL
      [Op.not]: true,                          // IS NOT TRUE
      [Op.or]: [5, 6],                         // (someAttribute = 5) OR (someAttribute = 6)

      // Using dialect specific column identifiers (PG in the following example):
      [Op.col]: 'user.organization_id',        // = "user"."organization_id"

      // Number comparisons
      [Op.gt]: 6,                              // > 6
      [Op.gte]: 6,                             // >= 6
      [Op.lt]: 10,                             // < 10
      [Op.lte]: 10,                            // <= 10
      [Op.between]: [6, 10],                   // BETWEEN 6 AND 10
      [Op.notBetween]: [11, 15],               // NOT BETWEEN 11 AND 15

      // Other operators

      [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1)

      [Op.in]: [1, 2],                         // IN [1, 2]
      [Op.notIn]: [1, 2],                      // NOT IN [1, 2]

      [Op.like]: '%hat',                       // LIKE '%hat'
      [Op.notLike]: '%hat',                    // NOT LIKE '%hat'
      [Op.startsWith]: 'hat',                  // LIKE 'hat%'
      [Op.endsWith]: 'hat',                    // LIKE '%hat'
      [Op.substring]: 'hat',                   // LIKE '%hat%'
      [Op.iLike]: '%hat',                      // ILIKE '%hat' (case insensitive) (PG only)
      [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (PG only)
      [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
      [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
      [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (PG only)
      [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (PG only)

      [Op.any]: [2, 3],                        // ANY ARRAY[2, 3]::INTEGER (PG only)

      // In Postgres, Op.like/Op.iLike/Op.notLike can be combined to Op.any:
      [Op.like]: { [Op.any]: ['cat', 'hat'] }  // LIKE ANY ARRAY['cat', 'hat']

      // There are more postgres-only range operators, see below
    }
  }
});

 

Posted by sungho88
,