Skip to content

A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.

update Question Count

aichy12688d1faa73dee
diff --git a/internal/migrations/migrations.go b/internal/migrations/migrations.go
index 20e07eb2..17cff250 100644
--- a/internal/migrations/migrations.go
+++ b/internal/migrations/migrations.go
@@ -62,6 +62,7 @@ var migrations = []Migration{
NewMigration("update user pin hide features", updateRolePinAndHideFeatures, true),
NewMigration("update question post time", updateQuestionPostTime, true),
NewMigration("add login limitations", addLoginLimitations, true),
+ NewMigration("update question answer count", updateQuestionCount, true),
}
// GetCurrentDBVersion returns the current db version
diff --git a/internal/migrations/v13.go b/internal/migrations/v13.go
new file mode 100644
index 00000000..ddef599c
--- /dev/null
+++ b/internal/migrations/v13.go
@@ -0,0 +1,43 @@
+package migrations
+
+import (
+ "fmt"
+
+ "github.com/answerdev/answer/internal/entity"
+ "github.com/segmentfault/pacman/log"
+ "xorm.io/xorm"
+)
+
+func updateQuestionCount(x *xorm.Engine) error {
+ //search all answers
+ answers := make([]entity.Answer, 0)
+ err := x.Find(&answers, &entity.Answer{Status: entity.AnswerStatusAvailable})
+ if err != nil {
+ return fmt.Errorf("get answers failed: %w", err)
+ }
+ questionAnswerCount := make(map[string]int)
+ for _, answer := range answers {
+ _, ok := questionAnswerCount[answer.QuestionID]
+ if !ok {
+ questionAnswerCount[answer.QuestionID] = 1
+ } else {
+ questionAnswerCount[answer.QuestionID]++
+ }
+ }
+ questionList := make([]entity.Question, 0)
+ err = x.Find(&questionList, &entity.Question{})
+ if err != nil {
+ return fmt.Errorf("get questions failed: %w", err)
+ }
+ for _, item := range questionList {
+ _, ok := questionAnswerCount[item.ID]
+ if ok {
+ item.AnswerCount = questionAnswerCount[item.ID]
+ if _, err = x.Update(item, &entity.Question{ID: item.ID}); err != nil {
+ log.Errorf("update %+v config failed: %s", item, err)
+ return fmt.Errorf("update question failed: %w", err)
+ }
+ }
+ }
+ return nil
+}