시퀄라이즈 쿼리문 정리

rkdghwnd·2023년 6월 11일
0

findAll

(해당 조건에 해당하는) 모든 데이터를 가져오는 메소드
데이터는 배열안에 여러객체가 들어있는 형태로 반환된다.

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

// users테이블 전체를 조회해서 그 결과값을 객체로 만들어 user변수에 넣어준다.
// 조건을 따로 적지 않으면 해당 테이블의 전체 데이터를 조회한다.
const user = User.findAll({}); 

console.log(user[0].comment) // [ {data},{data},{data},... ]

findOne

(해당 조건에 해당하는) 데이터 하나를 가져오는 메소드

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

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

// user변수에는 조회된 결과 객체가 들어있어서, 해당 테이블 컬럼들을 조회할수 있다.
console.log(user.comment) // findOne는 하나만 조회된다. users테이블에 comment필드를 조회하기

조건(attributes, where)

attributes 와 where 옵션을 이용해 조건을 걸고 원하는 데이터만 가져올 수 있다.
where의 조건에 부합하는 데이터 중 attributes의 데이터만 포함해 가져온다.

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;

조건에 사용하는 Op 객체

  • Op.gt : 초과 (greater than)
  • Op.gte : 이상 (greater than or equal to)
  • Op.lt : 미만 (less than)
  • Op.lte : 이하 (less than or equeal to)
  • Op.ne : 같지 않음 (not equal)
  • Op.in : 배열 요소 중 하나
  • Op.notIn : 배열 요소와 모두 다른
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') 
}

Create

DB에 새로운 데이터를 생성한다.
SQL에서의 create는 테이블을 만드는 거지만 시퀄라이즈의 create는 insert로 쓰인다.

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

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가 될 경우
}

정렬하기(Order)

데이터를 정렬하는 옵션
2차원 배열이라는 점에 주의하자.

User.findAll({
    attributes: ['name', 'age'],
    order: [ ['age', 'DESC'], ['name', 'ASC'] ]
});

페이징(limit, offset)

조회할 로우 개수는 limit으로

조회를 시작할 로우 위치는 offset으로 할 수 있다.

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

Update

데이터를 수정한다.
첫번째 인수(attributes)는 수정할 내용이고, 두번째 인수(where)는 어떤 로우를 수정할지에 대한 조건이다.

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

upsert

해당 데이터가 존재하면 update를 수행하고, 없으면 새롭게 추가한다

const [city, created] = await City.upsert({
  cityName: "York",
  population: 20000,
});
console.log(created); // true or false
console.log(city); // City object

Delete

데이터를 삭제한다.

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

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

include

관계되어 있는 모델(테이블)을 함께 가져오는 속성

const user = await User.findOne({
    include: [{ // join한다.
        model: Comment, // join할 테이블을 고른다.
    }]
});

console.log(user.Comments[0]); 
// 쿼리 결과인 user객체안에 Comments라는 키에 include한 comments테이블 쿼리들이 배열 값으로서 담겨 잇다.
// Comments 키의 이름은 User모델은 hasMany니까 복수형으로 자동으로 변환되서 생성된 것이다. (구분하기 편하게)
// => hasOne이면 단수형. M:N이면 항상 복수형.

.toJSON()

const fullUserWithoutPassword = await User.findOne({
      where: { id: req.params.id },
      attributes: {
        exclude: ["password"],
      },
      include: [
        {
          model: Post,
          attributes: ["id"],
        },
        {
          model: User,
          as: "Followings",
          attributes: ["id"],
        },
        {
          model: User,
          as: "Followers",
          attributes: ["id"],
        },
      ],
    });
    if (fullUserWithoutPassword) {
      const data = fullUserWithoutPassword.toJSON(); // 가져온 테이블 데이터를 사용할수있는 객체로 변환한다.
      data.Posts = data.Posts.length;
      data.Followings = data.Followings.length;
      data.Followers = data.Followers.length;
      res.status(200).json(data);
    } else {
      res.status(404).json("존재하지 않는 사용자입니다.");
    }
profile
rkdghwnd's dev story

0개의 댓글