forked from eddycjy/go-gin-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharticle.go
executable file
·102 lines (81 loc) · 2.36 KB
/
article.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package models
import "github.com/jinzhu/gorm"
type Article struct {
Model
TagID int `json:"tag_id" gorm:"index"`
Tag Tag `json:"tag"`
Title string `json:"title"`
Desc string `json:"desc"`
Content string `json:"content"`
CoverImageUrl string `json:"cover_image_url"`
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
State int `json:"state"`
}
func ExistArticleByID(id int) (bool, error) {
var article Article
err := db.Select("id").Where("id = ? AND deleted_on = ? ", id, 0).First(&article).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if article.ID > 0 {
return true, nil
}
return false, nil
}
func GetArticleTotal(maps interface{}) (int, error) {
var count int
if err := db.Model(&Article{}).Where(maps).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func GetArticles(pageNum int, pageSize int, maps interface{}) ([]*Article, error) {
var articles []*Article
err := db.Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Find(&articles).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return articles, nil
}
func GetArticle(id int) (*Article, error) {
var article Article
err := db.Where("id = ? AND deleted_on = ? ", id, 0).First(&article).Related(&article.Tag).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return &article, nil
}
func EditArticle(id int, data interface{}) error {
if err := db.Model(&Article{}).Where("id = ? AND deleted_on = ? ", id, 0).Updates(data).Error; err != nil {
return err
}
return nil
}
func AddArticle(data map[string]interface{}) error {
article := Article{
TagID: data["tag_id"].(int),
Title: data["title"].(string),
Desc: data["desc"].(string),
Content: data["content"].(string),
CreatedBy: data["created_by"].(string),
State: data["state"].(int),
CoverImageUrl: data["cover_image_url"].(string),
}
if err := db.Create(&article).Error; err != nil {
return err
}
return nil
}
func DeleteArticle(id int) error {
if err := db.Where("id = ?", id).Delete(Article{}).Error; err != nil {
return err
}
return nil
}
func CleanAllArticle() error {
if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Article{}).Error; err != nil {
return err
}
return nil
}