GORM - model
type User struct {
gorm.Model
Birthday time.Time
Age int
Name string `gorm:"size:255"` // reset string size
Num int `gorm:"AUTO_INCREMENT"` // auto increment
CreditCard CreditCard // One-To-One (hasOne, CreditCard.UserID as key)
Emails []Email // One-To-Many (hasMany, Email.UserID as key)
BillingAddressID sql.NullInt64
BillingAddress Address // One-To-One (belongTo, BillingAddressID as key)
ShippingAddressID int
ShippingAddress Address // One-To-One (belongTo, ShippingAddressID as key)
IgnoreMe int `gorm:"-"` // 忽略这个字段
Languages []Language `gorm:"many2many:user_languages;"` // Many-To-Many , link table: user_languages
}
type CreditCard struct {
gorm.Model
UserID uint
Number string `gorm:"default:'1234567890'"` // default value
}
type Email struct {
ID int
UserID int `gorm:"index"` // foreign key & index
Email string `gorm:"type:varchar(100);unique_index"` // sql type & unique_index
Subscribed bool
}
type Address struct {
ID int
Address1 string `gorm:"not null;unique"` // not null, unique
Address2 string `gorm:"type:varchar(100);unique"`
Post sql.NullString `gorm:"not null"`
}
type Language struct {
ID int
Name string `gorm:"index:idx_name_code"` // 與下行同名, 會合併產生一個index
Code string `gorm:"index:idx_name_code"`
}
gorm Model
gorm.Model = ID,CreatedAt,UpdatedAt,DeletedAt
Table Name
type User struct {} // default table name is `users`
Column Name
type User struct {
ID uint // column name is `id`
Name string // column name is `name`
CreatedAt time.Time // column name is `created_at`
Age int64 `gorm:"column:age_of_man"` // rename column to`age_of_man`
}
Last updated
Was this helpful?