reply_model.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package model
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/go-redis/redis/v8"
  7. "gorm.io/gorm"
  8. )
  9. // CommentReply 评论回复
  10. type CommentReply struct {
  11. *Model
  12. PostId int64 `json:"post_id" gorm:"post_id"` // POST ID
  13. UserId int64 `json:"user_id" gorm:"user_id"` // 用户ID
  14. CommentId int64 `json:"comment_id" gorm:"comment_id"` // 评论ID
  15. Ip string `json:"ip" gorm:"ip"` // IP地址
  16. IpLoc string `json:"ip_loc" gorm:"ip_loc"` // IP城市地址
  17. Content string `json:"content" gorm:"content"` // 评论内容
  18. Image string `json:"image" gorm:"image"` // 评论图片
  19. WithUserIds string `json:"with_user_ids" gorm:"with_user_ids"` // 被艾特的用户
  20. IsEssence int8 `json:"is_essence" gorm:"is_essence"` // 是否精选
  21. ReplyCount int64 `json:"reply_count" gorm:"reply_count"` // 回复数
  22. ThumbsUpCount int64 `json:"thumbs_up_count" gorm:"thumbs_up_count"` // 点赞数
  23. ReplyId int64 `json:"reply_id" gorm:"reply_id"` // 回复的id
  24. }
  25. // TableName 表名称
  26. func (*CommentReply) TableName() string {
  27. return "p_comment_reply"
  28. }
  29. type ReplyModel struct {
  30. conn *gorm.DB
  31. redis *redis.Client
  32. }
  33. func NewReplyModel(conn *gorm.DB, rdb *redis.Client) ReplyModel {
  34. return ReplyModel{
  35. conn: conn,
  36. redis: rdb,
  37. }
  38. }
  39. // Create 创建回复
  40. func (m *ReplyModel) Create(ctx context.Context, reply *CommentReply) error {
  41. err := m.conn.WithContext(ctx).Create(reply).Error
  42. if err != nil {
  43. return err
  44. }
  45. // 删除回复列表缓存
  46. m.ClearReplyListCache(ctx, reply.CommentId)
  47. return nil
  48. }
  49. // ClearReplyListCache 清除回复列表缓存
  50. func (m *ReplyModel) ClearReplyListCache(ctx context.Context, commentId int64) {
  51. pattern := fmt.Sprintf("reply:list:%d*", commentId)
  52. keys, err := m.redis.Keys(ctx, pattern).Result()
  53. if err != nil {
  54. return
  55. }
  56. if len(keys) > 0 {
  57. m.redis.Del(ctx, keys...)
  58. }
  59. }
  60. // GetReply 获取回复详情
  61. func (m *ReplyModel) GetReply(ctx context.Context, replyId int64) (*CommentReply, error) {
  62. var reply CommentReply
  63. err := m.conn.WithContext(ctx).Where("id = ?", replyId).First(&reply).Error
  64. if err != nil {
  65. return nil, err
  66. }
  67. return &reply, nil
  68. }
  69. // Delete 删除回复
  70. func (m *ReplyModel) Delete(ctx context.Context, replyId int64) error {
  71. return m.conn.WithContext(ctx).Model(&CommentReply{}).
  72. Where("id = ?", replyId).
  73. Updates(map[string]interface{}{
  74. "is_del": 1,
  75. "deleted_on": time.Now().Unix(),
  76. "modified_on": time.Now().Unix(),
  77. }).Error
  78. }