From ad48cb4196444972b8a222b95ecccd909d4fa25b Mon Sep 17 00:00:00 2001 From: Ke Chen Date: Mon, 8 Apr 2024 20:47:29 +0800 Subject: [PATCH] fix: ReviewVote load vote after vote --- danke/api/review.go | 4 ++++ danke/model/review.go | 15 ++++++++++++--- danke/schema/review.go | 9 ++++++--- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/danke/api/review.go b/danke/api/review.go index 30e7073..c9b393c 100644 --- a/danke/api/review.go +++ b/danke/api/review.go @@ -98,6 +98,8 @@ func ModifyReviewV1(c *fiber.Ctx) (err error) { review, err = FindReviewByID(DB, id, FindReviewOption{ PreloadHistory: true, PreloadAchievement: true, + PreloadVote: true, + UserID: user.ID, }) if err != nil { return @@ -196,6 +198,8 @@ func VoteForReviewV1(c *fiber.Ctx) (err error) { review, err = FindReviewByID(DB, reviewID, FindReviewOption{ PreloadHistory: true, PreloadAchievement: true, + PreloadVote: true, + UserID: user.ID, }) if err != nil { return err diff --git a/danke/model/review.go b/danke/model/review.go index 9043613..50f8f45 100644 --- a/danke/model/review.go +++ b/danke/model/review.go @@ -30,21 +30,30 @@ type Review struct { DownvoteCount int `json:"downvote_count" gorm:"not null;default:0"` ModifyCount int `json:"modify_count" gorm:"not null;default:0"` History ReviewHistoryList `json:"-"` - Vote ReviewVoteList `json:"-"` + Vote ReviewVoteList `json:"-" gorm:"foreignKey:ReviewID;references:ID"` UserAchievements []*UserAchievement `json:"-" gorm:"foreignKey:UserID;references:ReviewerID"` } type FindReviewOption struct { PreloadHistory bool PreloadAchievement bool + PreloadVote bool + UserID int } func (o FindReviewOption) setQuery(querySet *gorm.DB) *gorm.DB { if o.PreloadHistory { - querySet.Preload("History") + querySet = querySet.Preload("History") } if o.PreloadAchievement { - querySet.Preload("UserAchievements.Achievement") + querySet = querySet.Preload("UserAchievements.Achievement") + } + if o.PreloadVote { + if o.UserID != 0 { + querySet = querySet.Preload("Vote", "user_id = ?", o.UserID) + } else { + querySet = querySet.Preload("Vote") + } } return querySet } diff --git a/danke/schema/review.go b/danke/schema/review.go index fa6469a..2b745df 100644 --- a/danke/schema/review.go +++ b/danke/schema/review.go @@ -96,11 +96,14 @@ func (r *ReviewV1Response) FromModel( r.Rank = new(ReviewRankV1).FromModel(review.Rank) r.Remark = review.UpvoteCount - review.DownvoteCount - for _, vote := range review.Vote { - if vote.UserID == user.ID { - r.Vote = vote.Data + if user != nil { + for _, vote := range review.Vote { + if vote.UserID == user.ID { + r.Vote = vote.Data + } } } + r.History = make([]*ReviewHistoryV1Response, 0, len(review.History)) for _, history := range review.History { r.History = append(r.History, new(ReviewHistoryV1Response).FromModel(review, history, r.Rank))