Gorm 简单应用
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/plugin/soft_delete"
"log"
"os"
"time"
)
// odf和odfhistory共有的字段结构,单独列出来,然后不同的再在其自己的结构体中设计
type OdfModels struct {
ID int `json:"id" gorm:"column:id;primaryKey;autoIncrement;<-:false;comment:主键ID;not null"`
OdfSn string `json:"sn" gorm:"column:sn;index:idx_sn_deleted_time,unique,priority:1;comment:sn;not null"`
CreatedTime time.Time `json:"created_time" gorm:"column:created_time;autoCreateTime;type:datetime;<-:create;comment:创建时间;not null"`
LastUpdateTime time.Time `json:"last_update_time" gorm:"column:last_update_time;autoUpdateTime;type:datetime;comment:更新时间;not null"`
}
// ODF odf表 在这里DeletedTime使用的是gorm插件的变量类型,这样在Delete的时候会使用软删除的方式,这个变量在数据库的类型是int时间戳,并且在这里设计了sn和deleted_time的联合唯一,以及
type ODF struct {
OdfModels
Odfhistory []ODFHistory `gorm:"foreignKey:record_id"`
DeletedTime soft_delete.DeletedAt `json:"deleted_time" gorm:"column:deleted_time;default:0;type:int(11);index:idx_sn_deleted_time,unique,priority:2;comment:删除时间"`
}
func (t *ODF) TableName() string {
return "odf"
}
// ODFHistory odf历史记录 在这里DeletedTime使用的是gorm内置的变量类型,这样在Delete的时候会使用软删除的方式,这个变量在数据库的类型是datetime,这里deleted_time后面的tag 建立的联合索引不能删除,删除的话会建立一个sn的唯一索引,不符合历史记录这个设定了
type ODFHistory struct {
OdfModels
Action string `json:"action" gorm:"column:action;<-:create;comment:动作;not null"`
RecordID int `json:"record_id" gorm:"column:record_id;<-:create;comment:关联ID;not null"`
DeletedTime gorm.DeletedAt `json:"deleted_time" gorm:"column:deleted_time;index:idx_sn_deleted_time,unique,priority:2;comment:删除时间"`
}
func (t *ODFHistory) TableName