You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.0 KiB

  1. package vote
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. v1 "practice_ArticleVote_Go/api/vote/v1"
  6. )
  7. func (l *VoteLogic) GetAllVote(ctx context.Context, req *v1.VoteReq) (res *v1.VoteRes, err error) {
  8. res = &v1.VoteRes{
  9. Total: 0,
  10. Rows: []v1.Vote{},
  11. }
  12. query := `
  13. SELECT
  14. a.article_title AS articleTitle,
  15. v.id AS voteId,
  16. v.vote_title AS voteTitle,
  17. v.create_time AS createTime,
  18. v.deadline_time AS deadlineTime,
  19. v.status
  20. FROM article a
  21. INNER JOIN vote_poll v ON a.id = v.article_id
  22. WHERE a.user_id = ?
  23. AND a.vote_status = 1
  24. `
  25. conditions := []interface{}{req.UserId}
  26. if req.ArticleTitle != "" {
  27. query += " AND a.article_title LIKE ?"
  28. conditions = append(conditions, "%"+req.ArticleTitle+"%")
  29. }
  30. if req.VoteTitle != "" {
  31. query += " AND v.vote_title LIKE ?"
  32. conditions = append(conditions, "%"+req.VoteTitle+"%")
  33. }
  34. if req.CreateTime != nil && !req.CreateTime.IsZero() {
  35. query += " AND DATE(v.create_time) = ?"
  36. conditions = append(conditions, req.CreateTime)
  37. }
  38. if req.DeadlineTime != nil && !req.DeadlineTime.IsZero() {
  39. query += " AND DATE(v.deadline_time) = ?"
  40. conditions = append(conditions, req.DeadlineTime)
  41. }
  42. if req.Status != 0 {
  43. query += " AND v.status = ?"
  44. conditions = append(conditions, req.Status)
  45. }
  46. // 构造 countQuery:使用相同的 baseQuery 和 WHERE 条件,但只统计行数
  47. var cntResult struct{ Cnt int }
  48. countQuery := "SELECT COUNT(*) AS cnt FROM (" + query + ") AS subquery"
  49. err = g.DB().Ctx(ctx).
  50. Raw(countQuery, conditions...).
  51. Scan(&cntResult)
  52. res = &v1.VoteRes{
  53. Total: cntResult.Cnt,
  54. }
  55. if err != nil {
  56. return nil, err
  57. }
  58. query += " ORDER BY v.create_time DESC "
  59. query += " LIMIT ?, ? "
  60. offset := (req.Page - 1) * req.PageSize
  61. conditions = append(conditions, offset, req.PageSize)
  62. err = g.DB().Ctx(ctx).
  63. Raw(query, conditions...).
  64. Scan(&res.Rows)
  65. if err != nil {
  66. return nil, err
  67. }
  68. // 设置分页信息
  69. res.Page = req.Page
  70. res.PageSize = req.PageSize
  71. return res, nil
  72. }