mh_goadmin_server/app/admin/models/category.go

114 lines
2.4 KiB
Go
Raw Normal View History

2023-10-17 07:33:05 +00:00
package models
import (
"fmt"
"go-admin/app/admin/models/common"
2023-10-17 08:14:39 +00:00
orm "go-admin/common/global"
2023-10-17 07:33:05 +00:00
"gorm.io/gorm"
)
type Category struct {
Model
Name string `json:"name"` // 分类名称
Number string `json:"number"` //编号
Display int8 `json:"state"` // 1 展示 0 隐藏
2023-10-17 07:41:15 +00:00
Pid uint32 `json:"pid" gorm:"index"` //父分类的编号
2023-10-17 07:33:05 +00:00
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 == "" {
2023-10-17 08:14:39 +00:00
n, err := GenerateNumber(c.CooperativeBusinessId, c.Pid)
if err != nil {
return err
2023-10-17 07:33:05 +00:00
}
2023-10-17 08:14:39 +00:00
c.Number = n
2023-10-17 07:33:05 +00:00
}
return nil
}
2023-10-17 08:14:39 +00:00
// 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
}
}
2023-10-18 02:06:16 +00:00
// GetCategoryById 通过id获取分类
2023-10-17 08:14:39 +00:00
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
}
2023-10-18 08:22:54 +00:00
type CategoryModel struct {
Category
SubCategory []*CategoryModel
}
func GetCategoryList(bid uint32) ([]*CategoryModel, error) {
var list = make([]*CategoryModel, 0)
m := orm.Eloquent.Model(Category{})
err := m.Scopes(common.ScopeBusiness(bid)).Where("pid = ?", 0).Find(&list).Error
if err != nil {
return nil, err
}
for _, top := range list {
top.SubCategory = findChildCategory(top)
}
return list, nil
}
func findChildCategory(prev *CategoryModel) []*CategoryModel {
var cs []*CategoryModel
err := orm.Eloquent.Model(Category{}).Where("pid", prev.ID).Find(&cs).Error
if err != nil {
return nil
}
for _, c := range cs {
c.SubCategory = findChildCategory(c)
}
return cs
}