go - 无法将类型字符串用作 sql.NullString

标签 go orm go-gorm

我正在创建 gorm模型

// Day is a corresponding day entry
type Day struct {
    gorm.Model
    Dateday   string         `json:"dateday" gorm:"type:date;NOT NULL"`
    Nameday   string         `json:"nameday" gorm:"type:varchar(100);NOT NULL"`
    Something sql.NullString `json:"salad"`
    Holyday   bool           `json:"holyday"`
}

我正在使用 sql.NullString用于字段 Something因为它可能是NULL。

所以当我尝试执行一个典型的 gorm验证我的设置是否有效的示例:
    db.Create(&Day{
        Nameday:     "Monday",
        Dateday:     "23-10-2019",
        Something:   "a string goes here",
        Holyday:      false,
    })

我得到:

cannot use "a string goes here", (type string) as type sql.NullString in field value


Something 应该使用什么类型字段给定它可能是NULL?

最佳答案

sql.NullString type 实际上不是字符串类型,而是结构类型。它定义为:

type NullString struct {
    String string
    Valid  bool // Valid is true if String is not NULL
}
因此,您需要这样初始化它:
db.Create(&Day{
    Nameday:     "Monday",
    Dateday:     "23-10-2019",
    Something:   sql.NullString{String: "a string goes here", Valid: true},
    Holyday:     false,
})

作为替代方案,如果您想在初始化可空字符串时继续使用更简单的语法,您可以声明自己的可空字符串类型,让它实现 sql.Scannerdriver.Valuer接口(interface),并利用空字节发出 NULL值(value)。
type MyString string

const MyStringNull MyString = "\x00"

// implements driver.Valuer, will be invoked automatically when written to the db
func (s MyString) Value() (driver.Value, error) {
    if s == MyStringNull {
        return nil, nil
    }
    return []byte(s), nil
}

// implements sql.Scanner, will be invoked automatically when read from the db
func (s *String) Scan(src interface{}) error {
    switch v := src.(type) {
    case string:
        *s = String(v)
    case []byte:
        *s = String(v)
    case nil:
        *s = StringNull
    }
    return nil
}
有了这个,如果你声明字段 SomethingMyString 类型您可以按照最初的意图对其进行初始化。
db.Create(&Day{
    Nameday:     "Monday",
    Dateday:     "23-10-2019",
    // here the string expression is an *untyped* string constant
    // that will be implicitly converted to MyString because
    // both `string` and `MyString` have the same *underlying* type.
    Something:   "a string goes here",
    Holyday:     false,
})
请记住,这仅适用于无类型的常量,一旦你有一个类型为 string 的常量或变量。 ,以便能够将其分配给 MyString您需要使用显式转换。
var s string
var ms MyString

s = "a string goes here"
ms = s // won't compile because s is not an untyped constant
ms = MyString(s) // you have to explicitly convert

关于go - 无法将类型字符串用作 sql.NullString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60792313/

相关文章:

googleapi : Error 400: Dataset myProject:myDataset is still in use, resourceInUse

dictionary - 如何安全地允许当前访问go中的嵌套 map ?

go - 有什么方法可以摆脱 GORM 中的自动列蛇案例重命名?

go - 我可以以某种方式在结构中包含公式吗?

go - 如何在 golang etcd 客户端中设置一致性选项

orm - DDD : subclasses & root entities

java - 使用 spring Data JPA 将 sql 查询的结果映射到 pojo

python - SQLAlchemy:选择查询中对象的哪些列

go - 使用 gorm Golang lib 构建自定义查询

postgresql - 如何使用gorm从项目B中的go1.12 Flex实例连接到项目A中的GCP PostgreSQL 11 DB