• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    해결됨

댓글 기능에 db SELF JOIN을 걸어서 대댓글을 만들고 싶습니다.

20.03.10 21:34 작성 조회수 358

0

module.exports = (sequelize,DataTypes) => {
const Comment = sequelize.define('Comment', {
content:{
type: DataTypes.TEXT,
allowNull: false,
},
isDeleted:{
type:DataTypes.BOOLEAN,
allowNull:false,
defaultValue:false,
},
}, {
charset :'utf8mb4',
collate : 'utf8mb4_general_ci',
});

Comment.associate = (db) => {
db.Comment.belongsTo(db.User);
db.Comment.belongsTo(db.Post);
db.Comment.belongsTo(db.Comment,{as:'ReComment', foreignKey:'ParentId'});
};
return Comment;
};

다음과 같이 모델에 새로 관계 추가해줬구요

router.post('/:postId/comment/:parentId', isLoggedIn, async (req, res, next) => { // POST /api/post/10/comment/2
try {
const post = await db.Post.findOne({ where: { id: req.params.postId } });
if (!post) {
return res.status(404).send('\"message\": \"포스트가 존재하지 않습니다.\"');
}
const comment = await db.Comment.findOne({ where: { id: req.params.parentId } });
if (!comment) {
return res.status(404).send('\"message\": \"댓글이 존재하지 않습니다.\"');
}
const reComment = await db.Comment.create({
PostId: req.params.postId,
UserId: req.user.id,
content: req.body.content,
ParentId: req.params.parentId,
});
await post.addComment(reComment.id);
const comments = await db.Comment.findOne({
where: {
id: reComment.id,
},
include: [{
model: db.User,
attributes: ['id', 'nickname'],
}],
});
return res.json(comments);
} catch (e) {
console.error(e);
return next(e);
}
});

다음과 같이 라우터에도 추가해줘서 대댓글이 잘 생성이 되긴 합니다.

그런데 대댓글의 데이터 셋을 뽑아올 때 sequelize로 어떻게 뽑아와야할 지 모르겠더라구요.

일단 제가 작성한 코드는 다음과 같습니다.

router.get('/:id/comments', async (req, res, next) => {
try {
const post = await db.Post.findOne({ where: { id: req.params.id } });
if (!post) {
return res.status(404).send('\"message\": \"포스트가 존재하지 않습니다.\"');
}
const comments = await db.Comment.findAll({
where: {
PostId: req.params.id,
isDeleted:0,
ParentId : null,
},
order: [['createdAt', 'ASC']],
include: [{
model: db.User,
attributes: ['id', 'nickname'],
include:[{
model:db.Image,
attributes:['src']
}]
}, {
model: db.Comment,
as:'ReComment',
where: {
ParentId: Comment.id //해결하고싶은 부분
}
}],
});
res.json(comments);
} catch (e) {
console.error(e);
next(e);
}
});

해결하고싶은 부분이 바로 저부분입니다.  WHERE절에  db.Comment 의 id를 가져다가 사용하고싶은데요 어떤 함수를 사용해야하는지 공식문서를 찾아봐도 못찾겠더라구요 혹시 해결방법이 있을까요? 생 쿼리를 사용한다면

SELECT * FROM comments.Co

SELF JOIN comments.Re

ON Re.parentId = Co.id 

이런 느낌이겠네요.

답변 1

답변을 작성해보세요.

0

딱히 조건 안 적어주어도 include만으로 그 댓글의 대댓글 가져옵니다.