chat.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package db
  2. import (
  3. "errors"
  4. "strings"
  5. "gorm.io/gorm"
  6. )
  7. type ChatType uint
  8. const Q ChatType = 1
  9. const A ChatType = 2
  10. type Chat struct {
  11. gorm.Model
  12. Username string `gorm:"type:varchar(50);not null;comment:'用户名'" json:"username"` // 用户名
  13. Source string `gorm:"type:varchar(50);comment:'用户来源:群聊名字,私聊'" json:"source"` // 对话来源
  14. ChatType ChatType `gorm:"type:tinyint(1);default:1;comment:'类型:1问, 2答'" json:"chat_type"` // 状态
  15. ParentContent uint `gorm:"default:0;comment:'父消息编号(编号为0时表示为首条)'" json:"parent_content"`
  16. Content string `gorm:"type:varchar(128);comment:'内容'" json:"content"` // 问题或回答的内容
  17. }
  18. type ChatListReq struct {
  19. Username string `json:"username" form:"username"`
  20. Source string `json:"source" form:"source"`
  21. }
  22. // Add 添加资源
  23. func (c Chat) Add() (uint, error) {
  24. err := DB.Create(&c).Error
  25. return c.ID, err
  26. }
  27. // Find 获取单个资源
  28. func (c Chat) Find(filter map[string]interface{}, data *Chat) error {
  29. return DB.Where(filter).First(&data).Error
  30. }
  31. // List 获取数据列表
  32. func (c Chat) List(req ChatListReq) ([]*Chat, error) {
  33. var list []*Chat
  34. db := DB.Model(&Chat{}).Order("created_at ASC")
  35. userName := strings.TrimSpace(req.Username)
  36. if userName != "" {
  37. db = db.Where("username = ?", userName)
  38. }
  39. source := strings.TrimSpace(req.Source)
  40. if source != "" {
  41. db = db.Where("source = ?", source)
  42. }
  43. err := db.Find(&list).Error
  44. return list, err
  45. }
  46. // Exist 判断资源是否存在
  47. func (c Chat) Exist(filter map[string]interface{}) bool {
  48. var dataObj Chat
  49. err := DB.Where(filter).First(&dataObj).Error
  50. return !errors.Is(err, gorm.ErrRecordNotFound)
  51. }