관계를 설정했다면 getComments(조회) 외에도 setComments(수정), addComment(하나 생성), addComments(여러 개 생성), removeComments(삭제) 메서드를 지원합니다. 동사 뒤에 모델의 이름이 붙는 형식입니다.

    동사 뒤의 모델 이름을 바꾸고 싶다면 관계를 설정할 때 as 옵션을 사용할 수 있습니다.

    // 관계 설정할 때 as로 등록
    db.User.hasMany(db.Comment, { foreignKey: 'commenter', sourceKey: 'id', as: 'Answers' });
    // 쿼리할 때는
    const user = await User.findOne({});
    const comments = await user.getAnswers();
    console.log(comments); // 사용자 댓글

    as를 설정하면 include할 때 추가되는 댓글 객체도 user.Answers로 바뀝니다.

    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'],
    });
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.