Skip to content

Commit ec43caa

Browse files
update comment repo for updating count
1 parent c789a9a commit ec43caa

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

internal/repository/comment.go

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,19 @@ func NewCommentRepository(db *gorm.DB) *commentRepository {
1515
}
1616

1717
func (r *commentRepository) Create(comment *models.Comment) error {
18-
return r.db.Create(comment).Error
18+
return r.db.Transaction(func(tx *gorm.DB) error {
19+
if err := tx.Create(comment).Error; err != nil {
20+
return err
21+
}
22+
23+
if err := tx.Model(&models.Post{}).
24+
Where("id = ?", comment.PostID).
25+
UpdateColumn("comments_count", gorm.Expr("comments_count + ?", 1)).Error; err != nil {
26+
return err
27+
}
28+
29+
return nil
30+
})
1931
}
2032

2133
func (r *commentRepository) GetByID(id uint) (*models.Comment, error) {
@@ -35,7 +47,22 @@ func (r *commentRepository) Update(comment *models.Comment) error {
3547
}
3648

3749
func (r *commentRepository) Delete(id uint) error {
38-
return r.db.Delete(&models.Comment{}, id).Error
50+
return r.db.Transaction(func(tx *gorm.DB) error {
51+
var comment models.Comment
52+
if err := tx.First(&comment, id).Error; err != nil {
53+
return err
54+
}
55+
56+
if err := tx.Delete(&models.Comment{}, id).Error; err != nil {
57+
return err
58+
}
59+
60+
if err := tx.Exec("UPDATE posts SET comments_count = GREATEST(comments_count - 1, 0) WHERE id = ?", comment.PostID).Error; err != nil {
61+
return err
62+
}
63+
64+
return nil
65+
})
3966
}
4067

4168
func (r *commentRepository) ListByPostID(postID uint) ([]models.Comment, error) {

0 commit comments

Comments
 (0)