Sequelize CRUD 쿼리

2023. 7. 9. 20:52ORM/Sequelize

테이블 조회

FindAll

쿼리 결과를 배열 객체로 반환

모든 데이터를 조회하고 싶으면 findAll 메서드를 사용

 

const { User } = require('./models');

// users테이블 전체를 조회해서 그 결과값을 객체로 만들어 user변수에 넣어준다.
const user = User.findAll({}); 

// user변수에는 조회된 결과 객체가 들어있어서, 해당 테이블 컬럼들을 조회할수 있다.
console.log(user[0].comment) // findAll는 여러 행들을 조회하기에, 각 행들이 배열로 저장되어있다.
							 // 따라서 배열 인덱스로 조회한다. 첫번째 행 users테이블에 comment필드를 조회하기

FindOne

쿼리 결과를 객체로 반환

테이블의 데이터를 하나만 가져온다.

주로 where 절과 함께 사용된다.

 

const project = await Project.findOne({ where: { title: 'My Title' } });
if (project === null) {
  console.log('Not found!');
} else {
  console.log(project instanceof Project); // true
  console.log(project.title); // 'My Title'
}

FindByPk

쿼리 결과를 객체로 반환

primary key 를 이용하여 테이블의 데이터를 가져온다

const project = await Project.findByPk(123);
if (project === null) {
  console.log('Not found!');
} else {
  console.log(project instanceof Project); // true
  // Its primary key is 123
}

조건 조회(attributes, where)

attributes 옵션을 통해 원하는 컬럼만 가져올 수 있다.

where 옵션으로 조건들을 나열할 수 있다. where 옵션은 기본적으로 AND 옵션과 같다.

const { User } = require('./models');
const { Op } = require('sequelize');

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

console.log(user.comment)
SELECT name, age FROM users WHERE married = 1 AND age > 30;

시퀄라이즈는 자바스크립트 객체를 사용하여 쿼리를 생성하기 때문에 특수한 연산자들이 사용된다.

const Op = Sequelize.Op

[Op.and]: [{a: 5}, {b: 6}] // (a = 5) AND (b = 6)
[Op.or]: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)

[Op.gt]: 6,                // > 6
[Op.gte]: 6,               // >= 6

[Op.lt]: 10,               // < 10
[Op.lte]: 10,              // <= 10

[Op.ne]: 20,               // != 20
[Op.eq]: 3,                // = 3

[Op.is]: null              // IS NULL
[Op.not]: true,            // IS NOT TRUE

[Op.between]: [6, 10],     // BETWEEN 6 AND 10
[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15

[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.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.like]: { // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
	[Op.any]: ['cat', 'hat']
} 

[Op.gt]: { // > ALL (SELECT 1)
	[Op.all]: literal('SELECT 1') 
}

 

Op.or 예시)

const user = User.findAll({
    attributes: ['name', 'age'],
    where: { 
        [Op.or]: [ // married = 0 or age > 30
            { married: false },
            { age: { [Op.gt]: 30 } }
        ],
    },
});

console.log(user.comment)
SELECT name, age FROM users WHERE married = 1 OR age > 30;

데이터 넣기

create

모델을 불러와 create 메서드를 사용하여 row 를 생성한다.

const result = User.create({ // 생성된 쿼리 결과를 얻는다.
    name: 'beom seok',
    age: 23,
    married: false,
    comment: '안녕하세요.'
});

sequelize 모델에 정의한 자료형대로 넣어야 한다.

자료형 또는 옵션에 부합하지 않는 데이터를 넣을 경우 시퀄라이즈가 에러를 발생시키며, 시퀄라이즈가 알아서 MySQL 자료형으로 바꿔준다.

 

 

FindOrCreate()

조회 후에 없는 값이면 생성하고, 있는 값이면 그 값을 가져오는 형태의 오퍼레이션도 가능하다.

// find와 create 두 조건을 이행하기 때문에 반환값이 2개 즉 배열이다.
const [user, created] = await User.findOrCreate({
    where: { username: 'sdepold' },
    defaults: {
    job: 'Technical Lead JavaScript'
}
});
if (created) {
    // 만약 find하지 못하여 새로 create 될경우
    console.log(user.job); // 'Technical Lead JavaScript'
} else {
	// 만약 find가 될 경우
}

where 에 함께 전달되는 defaults 옵션은 검색 결과가 존재하지 않을 경우 새로 생성되는 요소가 갖는 기본값이다.

 


데이터 수정

update

update 메소드로 데이터를 수정할 수 있다.

User.update({
    comment: '새로운 코멘트.',
}, {
    where: { id: 2 },
});

Destroy

row 삭제는 destroy 메서드로 삭제.

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

User.destroy({
    where: { id: { [Op.in]: [1,3,5] } },
});

'ORM > Sequelize' 카테고리의 다른 글

Sequelize 관계 쿼리  (0) 2023.07.09
Sequelize 관계 정의하기  (0) 2023.07.09
Sequelize Model  (0) 2023.07.09
Sequelize Migration  (0) 2023.07.09
Sequelize 라이브러리 구성  (0) 2023.07.09