package models import ( "fmt" "go-admin/app/admin/models/common" "gorm.io/gorm" ) type Category struct { Model Name string `json:"name"` // 分类名称 Number string `json:"number"` //编号 Display int8 `json:"state"` // 1 展示 0 隐藏 Pid uint32 `json:"pid" gorm:"index"` //父分类的编号 CooperativeBusinessId uint32 `json:"cooperative_business_id"` //合作商id } func (c *Category) TableName() string { return "erp_category" } func (c *Category) BeforeCreate(tx *gorm.DB) error { if c.Number == "" { var count int64 var err error if c.Pid == 0 { err = tx.Model(c). Unscoped(). Scopes(common.ScopeCooperativeBusiness(c.CooperativeBusinessId)). Where("pid", ""). Count(&count). Error if err != nil { return err } c.Number = fmt.Sprintf("%03d", count) } else { var parent Category err = tx. Scopes(common.ScopeCooperativeBusiness(c.CooperativeBusinessId)). Where("id", c.Pid). First(&parent).Error if err != nil { return err } err = tx.Model(c). Unscoped(). Scopes(common.ScopeCooperativeBusiness(c.CooperativeBusinessId)). Where("pid", c.Pid). Count(&count). Error if err != nil { return err } c.Number = fmt.Sprintf("%s%03d", parent.Number, count) } } return nil }