시퀄라이즈 ORM (4)

김무연·2023년 12월 20일

Backend

목록 보기
46/49

관계 쿼리

  • findOne이나 findAll 메서드를 호출할 때 프로미스의 결과로 모델을 반환한다
    (findAll은 모델의 배열을 반환한다).
  • 결과 값이 객체로 받아와져, user.name, user.nick 식으로 호출이 가능하다
const user = await User.findOne({});
console.log(user.name);
  • User 모델의 정보에도 바로 접근할 수 있겠지만, 더 편리한 점은 관계 쿼리를 지원한다는 것이다. MySQL로 따지면 JOIN 기능이다. (관계 있는 것들을 엮을 수 있음)
const user = await User.findOne({
	include: [{
    	model: Comment,
    }]
});

console.log(user.comments)
  • 현재 User 모델은 Commenter 모델과 hasMany-belongsTo 관계가 맺어져 있으며, 만약 특정 사용자를 가져오면서 그 사람의 댓글까지 모두 가져오고 싶다면 include 속성을 사용한다.

  • 다대다 모델은 다음과 같이 접근 가능

db.sequelize.models.PostHashtag 

get + 모델명으로 관계 있는 데이터 로딩 가능

  • get을 붙이면 sequelize가 알아서 해당하는 모델명의 데이터를 가져와 준다!! (신기함)
const user = await User.findone({});
const comments = await user.getComments();
console.log(comments);
  • as 로 모델명 변경 가능, 하지만 include를 쓸 때 주의 include의 모델에서는 원래 모델이름을 넣어주고, 결과값을 반환할 때만 as의 별명으로 써줘야 함
db.User.hasMany(db.Comment, {foreignKey: 'commenter', sourceKey: 'id', as: 'Answers'});
// Answers로 테이블 명이 별명이 생김

const user = await User.findOne({});
const comments = await user.getAnswers();
console.log(comments);
  • include 나 관계 쿼리 메서드에서도 where나 attributes 가능
const user = await User.findOne({
	include: [{
    	model: Comment,
        where: {
        	id: 1,
        },
        attributes: ['id'],
    }]
});

또는

const comments = await user.getComments({
	where: {
    	id: 1,
    },
    attributes: ['id'],
});

조회는 위와 같지만, 생성, 수정, 삭제 쿼리는 조금 다르다

생성 쿼리

// 생성
const user = await User.findOne({ 옵션 }); // 참조 관계에 부합한 유저를 선택하고
const comment = await Comment.create({ 옵션 }); // 데이터를 comment테이블에 넣는다.

await user.addComment(comment); // user의 외래키를 관계설정된 comment row에 추가/업뎃 한다
// 만일 user의 외래키를 위 Comment.create()과정에서 넣었다면 굳이 addComment() 쿼리를 안날려도 된다.
// FK가 null허용이고 insert과정에서 FK에 데이터를 안넣었을 경우 사용하는 것이다.

// 여러 개 생성
const user = await User.findOne({ 옵션 });
const comment1 = await Comment.create({ 옵션 });
const comment2 = await Comment.create({ 옵션 });

await user.addComment([comment1, comment2]);
// SQL
insert into comments (필드) 
( select 필드 from user where 조건 )
  • 관계 쿼리 메서드의 인수로 추가할 댓글 모델을 넣거나 댓글의 아이디를 넣으면 된다.
    수정이나 삭제 또한 마찬가지이다.

  • 생성(입력) add+모델명, 수정은 set+모델명, 삭제는 remove+모델명

raw쿼리

직접 SQL을 쓸 수 있음

const [ result, metadata ] = await sequelize.query('SELECT * from comments');

console.log(result);

위 처럼 직접 sql 코드를 쳐 넣을 수 있다.

profile
Notion에 정리된 공부한 글을 옮겨오는 중입니다... (진행중)

0개의 댓글