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.

61 lines
1.4 KiB

  1. package article
  2. import (
  3. "context"
  4. "fmt"
  5. "practice_ArticleVote_Go/api/article"
  6. "practice_ArticleVote_Go/internal/dao"
  7. "practice_ArticleVote_Go/internal/service"
  8. )
  9. var ArticleController = &cArticle{}
  10. type cArticle struct {
  11. service service.IArticle
  12. }
  13. // 添加文章与投票
  14. func (c *cArticle) AddArticle(ctx context.Context, req *article.ArticleReq) (res *article.ArticleRes, err error) {
  15. var Aid int64 // 文章ID
  16. var Vid int64 // 投票活动ID
  17. type VoteOption struct {
  18. VoteId int64
  19. OptionContent string
  20. OptionIndex int
  21. Status int
  22. }
  23. var VoteOptions []VoteOption
  24. // 创建文章
  25. Aid, err = dao.Article.Ctx(ctx).Data(req).InsertAndGetId()
  26. if req.VoteStatus == 1 {
  27. req.ArticleId = Aid
  28. // 如果发起投票,创建投票活动
  29. Vid, err = dao.VotePoll.Ctx(ctx).Data(req).InsertAndGetId()
  30. if err != nil {
  31. return nil, fmt.Errorf("创建投票活动失败: %w", err)
  32. }
  33. // 如果发起投票,创建投票选项
  34. for _, option := range req.OptionList {
  35. VoteOptions = append(VoteOptions, VoteOption{
  36. VoteId: Vid,
  37. OptionContent: option.OptionContent,
  38. OptionIndex: option.OptionIndex,
  39. Status: 1,
  40. })
  41. }
  42. _, err = dao.VoteOption.Ctx(ctx).Data(VoteOptions).Insert()
  43. if err != nil {
  44. return nil, fmt.Errorf("创建投票选项失败: %w", err)
  45. }
  46. }
  47. if err != nil {
  48. return nil, fmt.Errorf("创建文章失败: %w", err)
  49. }
  50. return
  51. }