댓글 기능에 db SELF JOIN을 걸어서 대댓글을 만들고 싶습니다.
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
next 10 이상에서는 redux dev tool 구동이 안되나요?
0
272
1
세션 갱신 문의 건
0
483
7
배포 진행 후 Highlight updates components render 표시
0
445
1
똑같은 기능을 하는 테이블
0
447
4
관계형
0
312
2
프론트 서버를 이용하지 않는경우
1
299
3
인피니트 스크롤링 사용시 오류
0
278
0
계속 이런에러가 떠서 해결하기는 했는데 어떤 의미인지 모르겠습니다.
0
434
2
req.user가 언제 생성되나요??
0
330
2
Cannot read property 'id' of null 에러
0
333
1
리트윗한 게시글 불러오는 sequelize
0
252
1
result.data에서 images인 이유
0
281
2
takeLatest에 대한 질문입니다.
1
342
2
프론트에서 express를 사용하지 않을때 동적라우팅
0
501
6
getInitialProps가 클라이언트에서 수행되는 이유?
0
258
1
리로드하면 팔로우 언팔로우 값이 초기화 되는 문제입니다.
0
445
2
스타일드 컴포넌트와 className을 통한 스타일 적용의 차이에 대해 궁금합니다
0
585
2
할인 쿠폰 사용이 안되는되요 (848-f9af83f183e3)
0
365
1
nodejs mvc 패턴
0
975
4
사용하고 보니, 람다 구성이 궁금합니다!
0
266
1
제로초님
0
445
1
새로고침 로그인 풀림 문제.
0
247
1
안녕하세요. 강의 너무 감사합니다
0
157
1
제로초님
0
170
1





