我试图为 postgres 数据库创建一个 GORM 模型,其中包含一个带有自定义的类型Scanner
and Valuer
将字符串切片与字符串相互转换,以保存为单个数据库列。如果切片为空或 nil,我希望数据库列也为 nil(而不是空字符串)。
type MultiString []string
func (s *MultiString) Scan(src interface{}) error {
str, ok := src.(string)
if !ok {
return errors.New("failed to scan multistring field - source is not a string")
}
*s = strings.Split(str, ",")
return nil
}
func (s MultiString) Value() (driver.Value, error) {
if s == nil || len(s) == 0 {
return nil, nil
}
return strings.Join(s, ","), nil
}
当我尝试打电话时出现问题AutoMigrate
在以下结构上:
type Person struct {
ID int
Name string
Kids *MultiString
}
我多次收到以下错误:
[error] unsupported data type: &[]
In the Value
method, replace the returned nil
with sql.NullString{}
- This is incorrect, as Value
should not return another Valuer
.
问题是 GORM 不确定新定义的类型的数据类型应该是什么,所以它试图弄清楚。相反,应该显式定义该类型,或者使用模型中的标签 or by 在新类型上实现 gorm 方法
模型中的标记
type MyModel struct {
...
MyText MultiString `gorm:"type:text"`
}
这告诉 GORM 使用类型text
对于数据库列类型。使用此策略,每次在模型中使用新类型时都必须应用该标签。
GORM方法
可以在新数据类型上实现两个 GORM 方法来告诉 GORM 应使用哪种数据库类型:
GormDataType() string
GormDBDataType(db *gorm.DB, field *schema.Field) string
例子:
func (MultiString) GormDataType() string {
return "text"
}
func (MultiString) GormDBDataType(db *gorm.DB, field *schema.Field) string {
// returns different database type based on driver name
switch db.Dialector.Name() {
case "mysql", "sqlite":
return "text"
}
return ""
}
如果您使用的数据库类型之间的数据类型不同,则此选项很有用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)