const user = await User.findOne({});
console.log(user.name);
const user = await User.findOne({
include: [{
model: Comment,
}]
});
console.log(user.comments)
현재 User 모델은 Commenter 모델과 hasMany-belongsTo 관계가 맺어져 있으며, 만약 특정 사용자를 가져오면서 그 사람의 댓글까지 모두 가져오고 싶다면 include 속성을 사용한다.
다대다 모델은 다음과 같이 접근 가능
db.sequelize.models.PostHashtag
get + 모델명으로 관계 있는 데이터 로딩 가능
const user = await User.findone({});
const comments = await user.getComments();
console.log(comments);
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);
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+모델명
직접 SQL을 쓸 수 있음
const [ result, metadata ] = await sequelize.query('SELECT * from comments');
console.log(result);
위 처럼 직접 sql 코드를 쳐 넣을 수 있다.