Last active
November 12, 2018 13:45
-
-
Save gavinzhou/008b2ae9b2bf9b7e93a200dfd645fe50 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package models | |
import ( | |
"github.com/jinzhu/gorm" | |
"time" | |
) | |
type Article struct { | |
Model | |
TagID int `json:"tag_id" gorm:"index"` | |
Tag Tag `json:"tag"` | |
Title string `json:"title"` | |
Description string `json:"description"` | |
Content string `json:"content"` | |
CreatedBy string `json:"created_by"` | |
ModifiedBy string `json:"modified_by"` | |
State int `json:"state"` | |
} | |
func ExistArticleByID(id int) bool { | |
var article Article | |
db.Select("id").Where("id = ?", id).First(&article) | |
return article.ID > 0 | |
} | |
func GetArticleTotal(maps interface{}) (count int) { | |
db.Model(&Article{}).Where(maps).Count(&count) | |
return | |
} | |
func GetArticles(pageNum int, pageSize int, maps interface{}) (articles []Article) { | |
db.Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Find(&articles) | |
return | |
} | |
func GetArticle(id int) (article Article) { | |
db.Where("id = ?", id).First(&article) | |
db.Model(&article).Related(&article.Tag) | |
return | |
} | |
func EditArticle(id int, data interface{}) bool { | |
db.Model(&Article{}).Where("id = ?", id).Updates(data) | |
return true | |
} | |
func AddArticle(data map[string]interface{}) bool { | |
db.Create(&Article{ | |
TagID: data["tag_id"].(int), | |
Title: data["title"].(string), | |
Description: data["description"].(string), | |
Content: data["content"].(string), | |
CreatedBy: data["created_by"].(string), | |
State: data["state"].(int), | |
}) | |
return true | |
} | |
func DeleteArticle(id int) bool { | |
db.Where("id = ?", id).Delete(Article{}) | |
return true | |
} | |
func (article *Article) BeforeCreate(scope *gorm.Scope) error { | |
scope.SetColumn("CreatedOn", time.Now().Unix()) | |
scope.SetColumn("ModifiedOn", time.Now().Unix()) | |
return nil | |
} | |
func (article *Article) BeforeUpdate(scope *gorm.Scope) error { | |
scope.SetColumn("ModifiedOn", time.Now().Unix()) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment