File tree Expand file tree Collapse file tree 1 file changed +29
-2
lines changed
Expand file tree Collapse file tree 1 file changed +29
-2
lines changed Original file line number Diff line number Diff line change @@ -15,7 +15,19 @@ func NewCommentRepository(db *gorm.DB) *commentRepository {
1515}
1616
1717func (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
2133func (r * commentRepository ) GetByID (id uint ) (* models.Comment , error ) {
@@ -35,7 +47,22 @@ func (r *commentRepository) Update(comment *models.Comment) error {
3547}
3648
3749func (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
4168func (r * commentRepository ) ListByPostID (postID uint ) ([]models.Comment , error ) {
You can’t perform that action at this time.
0 commit comments