type Category struct {
BaseModel // 主键时间戳等
Name string `gorm:"type:varchar(20);not null"`
IsDirectory bool `gorm:"default:false" json:"is_directory" form:"is_directory"`
ParentID int32 `json:"parent_id"`
Level int32 `gorm:"type:int unsigned;not null;default:1"`
Path string `gorm:"type:varchar(40);not null;default:'-'"`
}
类似于Laravel的模型初始化函数,gorm也有自己的初始化函数,叫做钩子函数:
//BeforeCreate 钩子函数,用于创建分类之前初始化level和path
func (c *Category) BeforeCreate(tx *gorm.DB) (err error) {
if c.ParentID == 0 {
c.Level = 1
c.Path = "-"
} else {
c.Level = c.Parent().Level + 1
c.Path = c.Parent().Path + strconv.Itoa(int(c.ParentID)) + "-"
}
return
}
func (c *Category) Parent() *Category {
var category Category
global.MT_DB.Find(&category, c.ParentID)
return &category
}
文章评论