dicts.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "woord-core-service/global"
  6. "gorm.io/gorm"
  7. )
  8. var (
  9. ErrDictNotFound = fmt.Errorf("词库不存在")
  10. )
  11. // 词库
  12. type Dict struct {
  13. *gorm.Model
  14. // 词库名
  15. Name string
  16. // 单词标题
  17. ValueTitle string
  18. // 词义标题
  19. MeaningTitle string
  20. // 附加标题
  21. ExtraTitle string
  22. // 词库所有单词
  23. Words []Word
  24. // 所属用户 ID
  25. UserID uint
  26. }
  27. type DictResult struct {
  28. ID uint `json:"id"`
  29. Name string `json:"name"`
  30. ValueTitle string `json:"value"`
  31. MeaningTitle string `json:"meaning"`
  32. ExtraTitle string `json:"extra"`
  33. WordCount uint `json:"wordCount"`
  34. }
  35. // 列出所有词库
  36. func ListDicts(dict *Dict) ([]DictResult, error) {
  37. result := []DictResult{}
  38. if err := global.DB.Model(&Dict{}).Select("*, (?) AS word_count", global.DB.Model(&Word{}).Select("COUNT()").Where("dict_id = dicts.id")).Find(&result, dict, "user_id").Error; err != nil {
  39. return nil, err
  40. }
  41. return result, nil
  42. }
  43. // 获取词库
  44. func GetDict(dict *Dict) (*DictResult, error) {
  45. result := &DictResult{}
  46. if err := global.DB.Model(&Dict{}).Select("*, (?) AS word_count", global.DB.Model(&Word{}).Select("COUNT()").Where("dict_id = dicts.id")).Take(result, dict, "id", "user_id").Error; err != nil {
  47. if errors.Is(err, gorm.ErrRecordNotFound) {
  48. return nil, ErrDictNotFound
  49. }
  50. return nil, err
  51. }
  52. return result, nil
  53. }
  54. // 创建词库
  55. func CreateDict(dict *Dict) (*DictResult, error) {
  56. if err := global.DB.Select("name", "value_title", "meaning_title", "extra_title", "user_id").Create(dict).Error; err != nil {
  57. return nil, err
  58. }
  59. return &DictResult{
  60. ID: dict.ID,
  61. Name: dict.Name,
  62. ValueTitle: dict.ValueTitle,
  63. MeaningTitle: dict.MeaningTitle,
  64. ExtraTitle: dict.ExtraTitle,
  65. }, nil
  66. }