-
Notifications
You must be signed in to change notification settings - Fork 1
/
snippet_gin-curd-service.txt
75 lines (60 loc) · 2.29 KB
/
snippet_gin-curd-service.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
type $Name$Service struct{}
// Get$Name$List 获取$ChineseName$列表
func ($RECEIVER$ *$Name$Service) Get$Name$List(query request.$Name$Query, offset int, limit int) (list interface{}, total int64, err error) {
// 声明 $package$.$Name$ 类型的变量以存储查询结果
$name$List := make([]$package$.$Name$, 0)
// 准备数据库查询
db := global.GGB_DB.Model(&$package$.$Name${})
if query.Label != "" {
db = db.Where("label LIKE ?", "%"+query.Label+"%")
}
// 获取总数
err = db.Count(&total).Error
if err != nil {
return
}
// 获取分页数据
err = db.Offset(offset).Limit(limit).Order("created_at DESC").Find(&$name$List).Error
return $name$List, total, err
}
// Create$Name$ 创建$ChineseName$
func ($RECEIVER$ *$Name$Service) Create$Name$(req $package$.$Name$) (err error) {
//err = global.GGB_DB.Where("label = ?", req.Label).First(&$package$.$Name${}).Error
//if !errors.Is(err, gorm.ErrRecordNotFound) {
// return errors.New(fmt.Sprintf("$ChineseName$ %s 已存在", req.Label))
//}
// 创建 $name$ 记录
err = global.GGB_DB.Create(&req).Error
return err
}
// Get$Name$ 获取$ChineseName$详情
func ($RECEIVER$ *$Name$Service) Get$Name$($name$Id uint) ($name$ $package$.$Name$, err error) {
err = global.GGB_DB.Where("id = ?", $name$Id).First(&$name$).Error
return $name$, err
}
// Update$Name$ 更新$ChineseName$
func ($RECEIVER$ *$Name$Service) Update$Name$(req $package$.$Name$, $name$Id uint) (err error) {
var old$Name$ $package$.$Name$
// 从数据库中查找具有指定 ID 的数据
err = global.GGB_DB.Where("id = ?", $name$Id).First(&old$Name$).Error
if err != nil {
return err
}
//err = global.GGB_DB.Where("label = ? AND id != ?", req.Label, $name$Id).First(&$package$.$Name${}).Error
//if !errors.Is(err, gorm.ErrRecordNotFound) {
// return errors.New(fmt.Sprintf("$ChineseName$ %s 已存在", req.Label))
//}
$name$Map := map[string]interface{}{
"Label": req.Label,
"LabelCode": req.LabelCode,
"Description": req.Description,
}
// 更新用户记录
err = global.GGB_DB.Model(&old$Name$).Updates($name$Map).Error
return err
}
// Delete$Name$ 删除$ChineseName$
func ($RECEIVER$ *$Name$Service) Delete$Name$($name$Id uint) (err error) {
err = global.GGB_DB.Where("id = ?", $name$Id).Delete(&$package$.$Name${}).Error
return err
}