| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package model
- import (
- "errors"
- "fmt"
- "woord-core-service/global"
- "gorm.io/gorm"
- )
- var (
- ErrDictNotFound = fmt.Errorf("词库不存在")
- )
- // 词库
- type Dict struct {
- *gorm.Model
- // 词库名
- Name string
- // 单词标题
- ValueTitle string
- // 词义标题
- MeaningTitle string
- // 附加标题
- ExtraTitle string
- // 词库所有单词
- Words []Word
- // 所属用户 ID
- UserID uint
- }
- type DictResult struct {
- ID uint `json:"id"`
- Name string `json:"name"`
- ValueTitle string `json:"value"`
- MeaningTitle string `json:"meaning"`
- ExtraTitle string `json:"extra"`
- WordCount uint `json:"wordCount"`
- }
- // 列出所有词库
- func ListDicts(dict *Dict) ([]DictResult, error) {
- result := []DictResult{}
- 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 {
- return nil, err
- }
- return result, nil
- }
- // 获取词库
- func GetDict(dict *Dict) (*DictResult, error) {
- result := &DictResult{}
- 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 {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrDictNotFound
- }
- return nil, err
- }
- return result, nil
- }
- // 创建词库
- func CreateDict(dict *Dict) (*DictResult, error) {
- if err := global.DB.Select("name", "value_title", "meaning_title", "extra_title", "user_id").Create(dict).Error; err != nil {
- return nil, err
- }
- return &DictResult{
- ID: dict.ID,
- Name: dict.Name,
- ValueTitle: dict.ValueTitle,
- MeaningTitle: dict.MeaningTitle,
- ExtraTitle: dict.ExtraTitle,
- }, nil
- }
|