Gorm Struct Tags? #642
-
Why do we still need gorm struct tags on some struct fields? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
gorm struct tags are needed for automigrations to run. however, since we moved off gorm automigrate, here are my observations where struct tags are necessary: when there is a many to many (see) when there is a has many, with a differently named foreign key ID has many example from gorm // User has many CreditCards, UserID is the foreign key
type User struct {
gorm.Model
CreditCards []CreditCard
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
} explicit has many foreign key required (forgive the contrived example) // User has many CreditCards, CustomerID is the foreign key
type User struct {
gorm.Model
CreditCards []CreditCard `gorm:"foreignKey:CustomerID;"` // required bc foreign key != <this struct name>ID
}
type CreditCard struct {
gorm.Model
Number string
CustomerID uint
} for some reason we also need it in our root model's ID field to specify we're using type Model struct {
ID uuid.UUID `gorm:"default:uuid_generate_v4();" json:"id" example:"123e4567-e89b-12d3-a456-426614174000"`
// ...
} |
Beta Was this translation helpful? Give feedback.
gorm struct tags are needed for automigrations to run. however, since we moved off gorm automigrate, here are my observations where struct tags are necessary:
when there is a many to many (see)
when there is a has many, with a differently named foreign key ID
has many example from gorm
explicit has many foreign key required (forgive the contrived example)