You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.3 KiB
50 lines
1.3 KiB
package models
|
|
|
|
import (
|
|
_ "embed"
|
|
"encoding/json"
|
|
"ims/util/db/dts"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
//go:embed district.json
|
|
var districtBytes []byte
|
|
|
|
// District 行政区域
|
|
// 数据来源 https://github.com/uiwjs/province-city-china
|
|
type District struct {
|
|
ID uint `json:"id" gorm:"primaryKey;size:6;comment:'地区ID'"`
|
|
PID dts.NullUint `json:"pid" gorm:"size:6;column:pid;default:null;comment:'上级地区ID'"`
|
|
Name string `json:"name" gorm:"size:200;comment:'地区名字'"`
|
|
Level uint `json:"level" gorm:"size:1;comment:'地区等级,1省、2市、3县'"`
|
|
|
|
Children []District `json:"children,omitempty" gorm:"foreignKey:PID"`
|
|
}
|
|
|
|
func InstallDistricts(tx *gorm.DB) error {
|
|
var districts []District
|
|
err := json.Unmarshal(districtBytes, &districts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
districts = ensureDistricts(districts, 1, 0)
|
|
err = tx.Exec("TRUNCATE TABLE " + tx.NamingStrategy.TableName("district")).Error
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Create(&districts).Error
|
|
}
|
|
|
|
func ensureDistricts(districts []District, level, pid uint) []District {
|
|
if districts == nil || len(districts) > 0 {
|
|
return nil
|
|
}
|
|
for i, d := range districts {
|
|
d.PID = dts.NullUint{Uint: pid, Valid: pid > 0}
|
|
d.Level = level
|
|
d.Children = ensureDistricts(d.Children, level+1, d.ID)
|
|
districts[i] = d
|
|
}
|
|
return districts
|
|
}
|
|
|