작성
·
296
0
안녕하세요
One-to-Many 관계
ondelete : "cascade" 관련 질문이 있습니다
게시판을 만들어서, 댓글 테이블과 대댓글 테이블을 One-to-Many관계로 해서, 댓글을 지우면 해당 댓글에 달린 대댓글도 같이 삭제가 되도록
ondelete : "cascade" 설정을 했습니다.
models/commnet(댓글).js
const Sequelize = require("sequelize");
module.exports = class Comment extends Sequelize.Model {
static init(sequelize) {
return super.init(
{
reply: {
type: Sequelize.TEXT,
allowNull: false,
},
nick: {
type: Sequelize.STRING(50),
allowNull: false,
},
},
{
sequelize,
timestamps: true,
underscored: false,
modelName: "Comment",
tableName: "comments",
paranoid: true,
charset: "utf8",
collate: "utf8_general_ci",
}
);
}
static associate(db) {
db.Comment.belongsTo(db.Post);
db.Comment.belongsTo(db.User);
db.Comment.hasMany(db.Recomment, { onDelete: "CASCADE", hooks: true });
}
};
models/recomment(대댓글).js
const Sequelize = require("sequelize");
module.exports = class Recomment extends Sequelize.Model {
static init(sequelize) {
return super.init(
{
re_reply: {
type: Sequelize.TEXT,
allowNull: false,
},
nick: {
type: Sequelize.STRING(50),
allowNull: false,
},
UserId: {
type: Sequelize.INTEGER(40),
allowNull: false,
},
},
{
sequelize,
timestamps: true,
underscored: false,
modelName: "Recomment",
tableName: "recomments",
paranoid: true,
charset: "utf8",
collate: "utf8_general_ci",
}
);
}
static associate(db) {
db.Recomment.belongsTo(db.Comment);
db.Recomment.belongsTo(db.Post);
}
};
Sequelize 공식 문서에 따라( https://sequelize.org/docs/v6/other-topics/hooks/#one-to-one-and-one-to-many-associations )
db.Comment.hasMany(db.Recomment, { onDelete: "CASCADE", hooks: true });
db.Recomment.belongsTo(db.Comment);
다음과 같이 작성했습니다. (안 되어서 양쪽에 {onDelete: "CASCADE", hooks : true} 를 다 넣어보기도 했지만 역시나 안 되었습니다.)
DB는 MySQL을 사용하고 있습니다.
위와 같이 한 후, npm start 를 하여서 MySQL에서 comment테이블과 recomment테이블이 생성되었는데, association에 의해 생긴 CommentId 속성이 onDelete set null 로 되어 있어서, migration을 진행했습니다.
처음에는 changeColumn 을 실행했는데, CommentId 기존의 것은 그대로 있고, onDelete cascade가 적용된 CommnetId가 하나 더 생기는 이상한 일이 발생해서, removeColumn 을 migration으로 진행한 후, 아래와 같이 addColumn을 진행해서, MySQL에서는 원하는 설정으로 나왔습니다.
"use strict";
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
return queryInterface.addColumn("Recomments", "CommentId", {
type: Sequelize.INTEGER(40),
references: {
model: "comments",
key: "id",
},
onDelete: "CASCADE",
onUpdate: "CASCADE",
});
},
async down(queryInterface, Sequelize) {
return queryInterface.removeColumn("Recomments", "CommentId");
},
};
그런데
param.id로 CommentId를 받아와서 해당 id의 데이터를 comment테이블에서 삭제하도록 했을 때,
const CommentId = parseInt(req.params.id, 10);
await Comment.destroy({ where: { id: CommentId } });
comment테이블에서 삭제가 되었으나, recomment 테이블에서는 삭제가 되지 않습니다..ㅠ 어떻게 해야 할까요?
답변 1
0
여전히 안 되네요 ㅠㅠ