package models import ( "fmt" "go-admin/app/admin/models/common" orm "go-admin/common/global" "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 == "" { n, err := GenerateNumber(c.CooperativeBusinessId, c.Pid) if err != nil { return err } c.Number = n } return nil } // GenerateNumber 生成分类编码 func GenerateNumber(cid uint32, pid uint32) (string, error) { m := orm.Eloquent.Model(Category{}) var count int64 var err error if pid == 0 { err = m.Scopes(common.ScopeBusiness(cid)). Where("pid", 0). Count(&count). Error if err != nil { return "", err } return fmt.Sprintf("%03d", count), nil } else { var parent Category err = m. Scopes(common.ScopeBusiness(cid)). Where("id", pid). First(&parent).Error if err != nil { return "", err } err = m. Unscoped(). Scopes(common.ScopeBusiness(cid)). Where("pid", pid). Count(&count). Error if err != nil { return "", err } return fmt.Sprintf("%s%03d", parent.Number, count), nil } } // GetCategoryById 通过id获取分类 func GetCategoryById(id uint32) (*Category, error) { var c *Category err := orm.Eloquent.Model(c).Where("id", id).First(c).Error if err != nil { return nil, err } return c, nil }