在Go语言中,结构体(struct)的字段可以包含额外的值。

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

extra value in field in struct golang

问题

这个 "extra" 字段 gorm:"primary_key" 在创建结构体时有什么作用?

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
}

这个字段的作用是将 ID 字段标记为主键。在使用 GORM(Go语言的ORM库)创建数据库表时,gorm:"primary_key" 标签会告诉 GORM 将 ID 字段作为主键。这意味着 ID 字段将被用作唯一标识每个记录的字段。

英文:

What does this "extra" field gorm:"primary_key" do when creating a struct?

type Model struct {
    ID        uint `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
}

答案1

得分: 1

这是gorm包使用的一个标签,用于告知该包该字段将被用作主键。

请参考 https://github.com/jinzhu/gorm/blob/b9a39be9c5e77bb0bfebd516114a8a4d605c645a/model_struct.go#L135-L139

gormSettings := parseTagSetting(field.Tag.Get("gorm"))
if _, ok := gormSettings["PRIMARY_KEY"]; ok {
    field.IsPrimaryKey = true
    modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
}
英文:

It's a tag used by the gorm package to let the package know that the field will be used as a primary key

See https://github.com/jinzhu/gorm/blob/b9a39be9c5e77bb0bfebd516114a8a4d605c645a/model_struct.go#L135-L139

gormSettings := parseTagSetting(field.Tag.Get("gorm"))
if _, ok := gormSettings["PRIMARY_KEY"]; ok {
	field.IsPrimaryKey = true
	modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
}

答案2

得分: 0

这些是我所称之为“注解”的内容,它们被各种包(在这种情况下是gorm)用于提供有关如何处理类型的更多信息。最常见的情况是在数据传输对象(如JSON和XML)上看到它们,这两个包在大多数用例中都需要它们。

在这种情况下,你告诉gorm这个字段是一个主键。从对该包文档的粗略查看来看,它用于关系建模(例如设置类型以映射到关系型数据库或类似的内容),所以在这里看到可为空、主键或外键等内容是有道理的。

英文:

Those are what I call 'annotations' they're used by various packages (in this case gorm) to provide more information about how to handle the type. Most commonly you see them on data transfer objects (like json and xml), both packages require them in most use cases.

In this case you're telling gorm this field is a primary key. From a cursory glance at that packages docs it is for relational modeling (like setting up types to map to an rmdb or something of that nature) so it makes sense here to see things like nullable, pk or fk.

huangapple
  • 本文由 发表于 2015年4月16日 01:57:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/29657421.html
匿名

发表评论

匿名网友

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

确定