英文:
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
包使用的一个标签,用于告知该包该字段将被用作主键。
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
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论