Post 는 해당 pk 로 전부 지워지는데 comment는 postId 부분만 지워진다.

 

>> 지우는 순서의 문제다!!

router.delete('/:id', async (req, res) => {
    const id = req.params.id;
    await sequelize.transaction(async ()=>{
        
        await Post.destroy({where: {id: id}}); // 1
        await Comment.destroy({where: {postId: id}}); // 2
    })
    res.status(204).send();
})

여기서 1 이 지워지면  Comment에 있는 postId가 어디를 참조 하고 있는지 몰라서 NULL로 바뀌고

2 의 코드에서 지워야할 포스트를 찾을 수가 없으므로 코멘트가 지워지지 않는다.

 

!! 각 모델에서 foreignKey가 어떤 모델과 관계가 있는 지 꼭 확인을 하고 지우는 순서를 고려해야 한다.

router.delete('/:id', async (req, res) => {
    const id = req.params.id;
    await sequelize.transaction(async ()=>{
        await Comment.destroy({where: {postId: id}}); // 1
        await Post.destroy({where: {id: id}}); // 2
        
    })
    res.status(204).send();
})

+ Recent posts