Model query

✒️ 2025-05-26 15:13 내용 수정



SELECT - find 메소드

  1. Model.findAll() : 모든 행을 검색하며, SELECT * FROM 테이블명과 동일하다.
    • where 절을 추가하면 해당 조건에 맞는 모든 데이터를 출력한다.
    • 반환 형태는 배열로 반환하기 때문에 데이터를 출력할 때 반복문 형태로 출력해야 한다.
const test = Test.findAll();
  1. Model.findByPk(pk) : primary key로 데이터를 검색한다.
const test = Test.findByPk(10); // primarykey가 10인 데이터 검색
  1. Model.findOne() : 조건에 맞는 데이터 1개를 검색한다.
    • 반환 형태는 단일 객체이므로 데이터를 출력할 때 이 점을 고려해야 한다.
const test = Test.findOne({ where:{ name : 'test'} });
  1. Model.findAndCountAll() : findAll과 count를 합친 메소드로 페이지네이션(대량의 데이터를 페이지 단위로 나누어 표시하는 기술)을 할 때 유용하다.
    • limit(한 페이지에 표시될 항목)과 offset(가져올 데이터 시작 위치)으로 데이터를 얻고, 특정 조건에 맞는 행의 개수를 출력할 때 사용한다.
    • group이 없다면 count는 query문 조건에 부합하는 행의 개수(정수)를, rows는 행을 반환한다.
    • group이 있다면 count는 각 그룹의 수와 프로젝트 된 속성(projected attribute)를, rows는 행을 반환한다.
const { Op } = require('sequelize');

const { count, rows } = await Test.findAndCountAll({
	where: {
		name: {
			[Op.like]: '%test%'
		}
	},
	offset: 10, // 가져올 데이터의 시작 위치
	limit: 5 // 한 페이지에 표시될 항목
});

SELECT - Column을 추가 및 제외하고 검색

  1. Model.findAll()에서 특정 column만 출력하고 별칭 부여하기
const test = Test.findAll({
	attributes: ['id', 'name'] // SELECT id, name FROM Test
});

// 별칭 부여하기
const test = Test.findAll({
	attributes: ['id', ['name', '이름']] // SELECT id, name AS 이름 FROM Test
});

// sequelize.fn을 할용한 Count 결과에 별칭 부여하기
const test = Test.findAll({
	attributes: [
		'abc', 
		[sequelize.fn('COUNT', sequelize.col('def')), 'n_def'] // SELECT abc, COUNT(def) AS n_def FROM Test
});
  1. Model.findAll()에서 전체 column과 특정 column을 추가하여 검색하기
const test = Test.findAll({
	attributes: {
		include: [
			[sequelize.fn('COUNT', sequelize.col('def')), 'n_def'] // SELECT *, COUNT(def) AS n_def FROM Test
		]
	}
});
  1. Model.findAll()에서 특정 column을 제외하고 검색하기
const test = Test.findAll({
	attributes: { exclude: ['name']} // SELECT ..., ..., ... FROM Test (name만 제외)
});

INSERT

  1. Model.build()Model.save()를 사용하는 방법
// create에 바로 객체를 입력하는 방법
const test = Test.build({id : 1, name : 'test'});
await.test.save();


// 객체를 전달하는 방법
const newTest = {
	id : 2,
	name : 'newTest'
}
const test2 = Test.create(newTest);
await test2.save();
  1. Model.create()를 사용하는 방법
// create에 바로 객체를 입력하는 방법
const test = await Test.create({id : 1, name : 'test'});

// 객체를 전달하는 방법
const newTest = {
	id : 2,
	name : 'newTest'
}
const test2 = await Test.create(newTest);

UPDATE

  1. Model.findOne()으로 데이터를 찾고, 객체의 properties를 새로 저장
// 수정할 내용
const newTest = {
	name : 'newTest'
}

// 수정할 행의 정보를 가져옴
const test = await Test.findOne({where:{id}}); 

// newInfo 객체 내의 모든 순회 가능한 property와 method를 String 배열로 반환
Object.keys(newTest).forEach((prop) => {
	test[prop] = newTest[prop] // property의 내용을 새 value로 저장
});

await test.save(); // 변경 내용을 저장
  1. Model.upate()를 사용하는 방법
// 객체를 바로 입력하여 조건에 맞는 내용을 수정
const test = await Test.update({name: 'updateTest'}, {
	where: {name: null}
});

// 생성된 객체를 전달하여 내용을 수정
const newTest = {
	name : 'newTest'
}

const test2 = await Test.update(newTest, {
	where: {name: null}
});

DELETE

await Test.destroy({
	where: {
		name: "test"
	}
});

WHERE 절

  1. 기본 형태
const test = Test.findAll({
	where: {
		id : 1
	}
}); // SELECT * FROM test WHERE id = 1

// Op 가져오기
const { Op } = require('sequelize');
// 위와 동일한 query문
const test = Test.findAll({
	where: {
		id : {
			[Op.eq] : 1
		}
	}
}); // SELECT * FROM test WHERE id = 1
  1. AND 조건
const test = Test.findAll({
	where: {
		id : 1,
		name : 'test'
	}
}); // SELECT * FROM test WHERE id = 1 AND name = 'test'

// Op 가져오기
const { Op } = require('sequelize');
// 위와 동일한 query문
const test = Test.findAll({
	where: {
		[Op.and]: [
			{id : 1},
			{name: 'test'}
		]
	}
}); // SELECT * FROM test WHERE id = 1 AND name = 'test'
  1. OR 조건
const { Op } = require('sequelize');

const test = Test.findAll({
	where: {
		[Op.or]: [
			{id: 1},
			{id: 3}
		]
	}
}); 
// SELECT * FROM test WHERE id = 1 OR id = 3
// SELECT * FROM test WHERE id IN [1, 3]

// 위와 동일한 query문
const test = Test.findAll({
	where: {
		id: {
			[Op.or]: [1, 3]
		}
	}
});
// SELECT * FROM test WHERE id = 1 OR id = 3
// SELECT * FROM test WHERE id IN [1, 3]
let musicList = await Music.findAll({
  where: {
	genreList: literal(`JSON_CONTAINS(genreList, '${genreId}')`),
	userId : userId
  },
  order: [['publishDate', 'DESC']]
});
let musicList= await Music.findAll({
  where: Sequelize.and(
		  Sequelize.where(
			Sequelize.fn('lower', Sequelize.col('musicName')), 
			{[Op.like]:`%${name.toLowerCase()}%`}
		  ),
		{userId}
	  )
});