Sequelize query

손연주·2021년 10월 29일
2
post-thumbnail
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.iLike]: '%hat'         // ILIKE '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat'      // NOT ILIKE '%hat'  (PG only)
[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.iRegexp]: '^[h|a|t]'    // ~* '^[h|a|t]' (PG only)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (PG only)
[Op.like]: { [Op.any]: ['cat', 'hat']}
                           // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
[Op.overlap]: [1, 2]       // && [1, 2] (PG array overlap operator)
[Op.contains]: [1, 2]      // @> [1, 2] (PG array contains operator)
[Op.contained]: [1, 2]     // <@ [1, 2] (PG array contained by operator)
[Op.any]: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)

[Op.col]: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example
[Op.gt]: { [Op.all]: literal('SELECT 1') }
                          // > ALL (SELECT 1)

Where

a and b 모두 만족하는 값 찾기

[Op.and] : [{value},{value}]

const Sequelize = require("sequelize")
const Op = Sequelize.Op

authenticateUser: async (email, password) => await User.findAll({
  where: { 
    [Op.and]: [{ email }, { password }] 
  } 
})

값이 없는 건 찾지 않기

[Op.ne] : null || undefined || ..

where: {
		user_id: id,
		singlepost_id: {
			[Op.ne]: null, //값이 null인 걸 제외하고 찾아준다
		},	
},

"가나다라"에서 "가나"로만 찾아도 나오게 하기

[Op.substring] & [Op.like]

where: {
	title: {
		[Op.substring]: title,
	},
}
        
// 참고로 이 둘은 같다
[Op.like]: "%" + title + "%",
[Op.substring]: title,

substring은 기본으로 "%" + 인자 + "%"이며
like는 원하는 대로 설정하여 쓸 수 있다

raw 옵션

findOne() 및 findAll()에서 json형태로 보거나 가공하고 싶을 때 사용한다.

Description.findAll({
	raw: true,
 	 ...
	},
}),

결과

[
  {
    key1: value1,
    key2: value2
  }
];

raw 옵션을 안 썼을 때

{
  key1 : value1,
  key2: [
    {
      key2_2: value2
    }
  ]
}

Attributes

attributes: ["column1", "column2", ...],

일반적으로 테이블의 열(Column)이다. 응답으로 받을 데이터에 나타내고 싶은 컬럼 값을 적어주면 된다.

Like.findAll({
	attributes: ["id", "user_id", "singlepost_id"],
	where: {
		user_id: id,
		singlepost_id: {
			[Op.ne]: null,
		},
	},
}),

ORDER (ASC, DESC 정렬)

order: [["column", "DESC"]]

오름차순(ASC) : 1,2,3,4 ... , ㄱ,ㄴ,ㄷ ... A,B,C ...
내림차순(DESC) : 10,9,8,7,6 ...

order: [["id", "DESC"]], // 최신순으로 보여주기 위해 내림차순으로 설정
order: [["title", "ASC"]], // 가장 정확한 검색값을 보여주기 위해 오름차순으로 설정

Like.findAll({
	raw: true,
	attributes: ["id", "user_id", "gallerypost_id"],
	order: [["id", "DESC"]],
	where: { ... }
})

콘솔에 쿼리 안 뜨게하기

Executing (default): INSERT INTO `Descriptions` (`id`,`title`,`genre`,`director`,`released`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?,?);
Executing (default): SELECT `id`, `title`, `title_eng`, `genre`, `director`, `released` FROM `Descriptions` AS `Description` WHERE `Description`.`title_eng` LIKE '%타짜%';

데이터 탈취나 리소스 절약을 위해서 위같은 쿼리는 개발모드일 때에만 콘솔에 찍히는 게 좋다. config 파일에 logging 옵션을 작성한다.

"development": {
    "database": "database",
    "username": "root",
    "password": "root",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "logging": false
}

참고

profile
할 수 있다는 생각이 정말 나를 할 수 있게 만들어준다.

0개의 댓글