[TIL] Sequelize 문법 23.07.05

이상훈·2023년 7월 6일
1

[내일배움캠프]

목록 보기
39/68

✔️오늘 한일!

  • Node.js 심화 1-13까지 수강
  • level 4 과제 시작

조건 조회
attributes 옵션을 사용하여 원하는 컬럼을 가져오거나, where을 사용하여 조건들을 나열할 수 있음

  const result = await Posts.findOne({
    attributes: ["postId", "userId", "title", "nickname", "content", "createdAt", "updatedAt"],
    where: { postId },
  });

where에는 Op객체를 사용할 수 있음

const { Op } = require("sequelize");
const { Posts } = require("./models");
Posts.findAll({
  where: {
    [Op.and]: { a: 5 }, // AND (a = 5)
    [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.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.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
  },
});

정렬
order는 2차원 배열로써 컬럼 하나가 아닌 두개 이상도 가능하다.

 order: [
        [Sequelize.literal("likes"), "DESC"],
        ["createdAt", "DESC"],
      ],

페이징
조회할 로우 개수는 limit으로,
조회를 시작할 로우 위치는 offset으로 할 수 있다.

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

Get
include로도 관계를 맺어 쿼리를 날릴 수 있지만 좀 더 간편한 문법

const user = await User.findOne({})
const posts = user.getLikes()
// 괄호 안에서 attributes와 where도 사용할 수 있음
  • getLikes() -> 조회
  • setLikes() -> 수정 (단, 통째로 지우고 추가하는 방식)
  • addLikes() -> 생성
  • removeLikes() -> 삭제

쿼리 문자열
literal()을 사용하여 쿼리문자열을 추가해 줄 수 있음

    const postLike = await Posts.findAll({
      attributes: [
        "postId",
        "userId",
        "nickname",
        "title",
        "createdAt",
        "updatedAt",
        [
          Sequelize.literal(`(SELECT COUNT(*) FROM Likes WHERE Likes.PostId = Posts.postId)`),
          "likes",
        ],
      ],
      include: [
        {
          model: Likes,
          attributes: [],
          where: { UserId: userId },
          required: true,
        },
      ],
      order: [
        [Sequelize.literal("likes"), "DESC"],
        ["createdAt", "DESC"],
      ],
    });
    return res.status(200).json({
      posts: postLike,
    });

참고 블로그 ① : https://inpa.tistory.com
참고 블로그 ② : https://velog.io/@source39

profile
코린이

0개의 댓글