-
Sequelize를 이용한 대댓글 기능 구현Today I Learned 2020. 1. 21. 11:04
DB 스키마
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters// 스키마 정의 const Comment = sequelize.define( // 테이블 이름 "Comment", { // 속성명 // 댓글 idx commentIdx: { // 데이터 타입 설정 type: DataTypes.INTEGER(11), // null 허용 안함 allowNull: false, // 기본키 primaryKey: true, // 자동 증가 autoIncrement: true }, name: { type: DataTypes.STRING(45), allowNull: false }, // 댓글 내용 content: { type: DataTypes.STRING(1000), allowNull: false }, // 부모 댓글 idx ref_comment: { type: DataTypes.INTEGER(11), allowNull: true }, createdAt: { type: DataTypes.DATE(), allowNull: false }, updatedAt: { type: DataTypes.DATE(), allowNull: false } }, {} ); ref_comment에 참조할 부모 댓글을 지정한다. 자기 자신이 부모일 경우에는 자기 자신의 idx 값을 넣는다.
/routes/boards/index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters// 게시글 상세 조회 함수 호출 let result = await models.Board.findAll({ include: [models.Comment], where: { boardIdx : boardIdx }, order: [ [models.Comment, 'ref_comment', 'ASC'], [models.Comment, 'commentIdx', 'ASC'] ] }); 1차 정렬은 ref_comment로 하고, ref_comment가 일치할 경우에는 commentIdx를 이용해 오름차순 정렬을 하면 순서대로 출력할 수 있다.
'Today I Learned' 카테고리의 다른 글
http vs https vs http2 (0) 2020.01.22 timezone issue (0) 2020.01.21 form 기본값 주기 (0) 2020.01.21 form에서 put, delete를 지원하지 않는 이유 (0) 2020.01.18 sequelize include (0) 2020.01.18