如何在gorm中从另一个包中添加默认值

huangapple go评论83阅读模式
英文:

How to add default value in gorm from another package

问题

我有一个定义如下的结构体:

type User struct {
    Name       string    `gorm:"type:varchar(100);size:100;not null;default:null;" json:"name"`
    UserTypeId uuid.UUID `sql:"type:uuid REFERENCES usertype(id);" gorm:"index;not null;default:null;" json:"user_type_id"`
    Score      int       `gorm:"size:36;index;not null;default:null;" json:"score"`
}

现在我想在另一个包中使用一些常量,比如将defaultID设置为'1234',而不是将null作为UserTypeID的默认值。我该如何在gorm的默认值中提及这个常量?我不想这样写:

UserTypeId sql:"type:uuid REFERENCES usertype(id);" gorm:"index;not null;default:1234;" json:"user_type_id"`

我希望能从一个定义好的常量中获取ID。

英文:

I have a struct defined as

type User struct {
    Name string `gorm:"type:varchar(100);size:100;not null;default:null;" json:"name"`
    UserTypeId uuid.UUID sql:"type:uuid REFERENCES usertype(id);" gorm:"index;not null;default:null;" json:"user_type_id"`
    Score int gorm:"size:36;index;not null;default:null;" json:"score"`
}

Now i want to use some contant defined in another package lets say defaultID = '1234'instead of null as default in UserTypeID how do i mention this constant inside gorm default value also i dont want to put it like this

 UserTypeId    sql:"type:uuid REFERENCES usertype(id);" gorm:"index;not null;default:1234;" json:"user_type_id"`

Instead of directly mentioning the id i want to take it from a constant defined.

答案1

得分: 1

你可以使用BeforeSaveBeforeUpdate钩子来实现这个功能。例如:

func (u *User) BeforeSave(tx *gorm.DB) error {
  //首先,检查UserTypeId的值

  //其次,更新该值
  u.UserTypeId = defaultID
}
英文:

You can achieve this with BeforeSave or BeforeUpdate hooks. For example:

func (u *User) BeforeSave(tx *gorm.DB) error {
  //first, check the UserTypeId value

  //second, update the value
  u.UserTypeId = defaultID
}

答案2

得分: 0

结构标签无法从字符串常量中构建。这是设计如此

然而,你可以使用反射包来实现这一点,但不建议这样做。

英文:

Struct tags can't be built from string constants. This is by design.

However, you can achieve this using reflect package but not recommended.

huangapple
  • 本文由 发表于 2021年8月31日 14:00:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/68993580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定