Skip to content

Commit 7ce6b0e

Browse files
committed
refactor(models): 将User.Groups的默认值逻辑迁移到BeforeCreate钩子
将Groups字段的默认值设置从gorm标签迁移到BeforeCreate钩子函数中,使默认值逻辑更灵活可控
1 parent 6bd4ff4 commit 7ce6b0e

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

backend/models/user.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,21 @@ type User struct {
1010
ID uint `json:"id" gorm:"primaryKey"`
1111
Username string `json:"username" gorm:"not null;unique"`
1212
Email string `json:"email" gorm:"not null;type:varchar(191)"`
13-
Role string `json:"role" gorm:"not null;default:user"` // admin or user (legacy)
14-
Groups string `json:"groups" gorm:"type:text;default:'t0'"` // CZL Connect权限组: t0,t1,t2,t3,t4,t5,viewer,admin
13+
Role string `json:"role" gorm:"not null;default:user"` // admin or user (legacy)
14+
Groups string `json:"groups" gorm:"type:text"` // CZL Connect权限组: t0,t1,t2,t3,t4,t5,viewer,admin
1515
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
1616
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
1717
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
1818
}
1919

20+
// BeforeCreate GORM hook: 在创建用户前设置默认值
21+
func (u *User) BeforeCreate(tx *gorm.DB) error {
22+
if u.Groups == "" {
23+
u.Groups = "t0"
24+
}
25+
return nil
26+
}
27+
2028
type Session struct {
2129
ID string `json:"id" gorm:"primaryKey"`
2230
UserID uint `json:"user_id" gorm:"not null"`

0 commit comments

Comments
 (0)