58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
|
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 string `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 == "" {
|
||
|
err = tx.Model(c).
|
||
|
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("number", c.Pid).
|
||
|
First(&parent).Error
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
err = tx.Model(c).
|
||
|
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
|
||
|
}
|