Skip to main content

数据库gorm

官网: https://gorm.io/zh_CN/

文档: https://gorm.io/zh_CN/docs/

常见问题

自定义返回的Json格式名称

type VideoList struct {
Model

Id uint `json:"id"`
Vid int64 `json:"vid"`
Author string `json:"author"`
VideoSrc string `json:"video_src"`
Thumbnail string `json:"thumbnail"`
Title string `json:"title"`
PublishTime int32 `json:"publish_time"`
PlayCnt int32 `json:"play_cnt"`
PageUrl string `json:"page_url"`
PraiseNum int32 `json:"praise_num"`
VideoInfo string `json:"video_info"`
AuthorId int64 `json:"author_id"`
AuthorIcon string `json:"author_icon"'`
TypeName string `json:"type_name"`
}
{
"id": 1,
"vid": 111,
"author": "11ss",
"video_src": "sss",
"thumbnail": "ss",
"title": "1dd1",
"publish_time": 111,
"play_cnt": 111,
"page_url": "vcsdca",
"praise_num": 111,
"video_info": "厄齐尔群",
"author_id": 111,
"author_icon": "驱蚊器",
"type_name": "去驱蚊器"
}

自动修改创建时间和更新时间的设置

func (tag *VideoList) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("CreatedOn", time.Now().Unix())

return nil
}

func (tag *VideoList) BeforeUpdate(scope *gorm.Scope) error {
scope.SetColumn("ModifiedOn", time.Now().Unix())

return nil
}

这属于gorm的Callbacks,可以将回调方法定义为模型结构的指针,在创建、更新、查询、删除时将被调用,如果任何回调返回错误,gorm 将停止未来操作并回滚所有更改。

gorm所支持的回调方法:

  • 创建:BeforeSave、BeforeCreate、AfterCreate、AfterSave
  • 更新:BeforeSave、BeforeUpdate、AfterUpdate、AfterSave
  • 删除:BeforeDelete、AfterDelete
  • 查询:AfterFind