Models

Model Definition

  1. type User struct {
  2. gorm.Model
  3. Birthday time.Time
  4. Age int
  5. Name string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
  6. Num int `gorm:"AUTO_INCREMENT"`
  7. CreditCard CreditCard // One-To-One relationship (has one - use CreditCard's UserID as foreign key)
  8. Emails []Email // One-To-Many relationship (has many - use Email's UserID as foreign key)
  9. BillingAddress Address // One-To-One relationship (belongs to - use BillingAddressID as foreign key)
  10. BillingAddressID sql.NullInt64
  11. ShippingAddress Address // One-To-One relationship (belongs to - use ShippingAddressID as foreign key)
  12. ShippingAddressID int
  13. IgnoreMe int `gorm:"-"` // Ignore this field
  14. Languages []Language `gorm:"many2many:user_languages;"` // Many-To-Many relationship, 'user_languages' is join table
  15. }
  16. type Email struct {
  17. ID int
  18. UserID int `gorm:"index"` // Foreign key (belongs to), tag `index` will create index for this column
  19. Email string `gorm:"type:varchar(100);unique_index"` // `type` set sql type, `unique_index` will create unique index for this column
  20. Subscribed bool
  21. }
  22. type Address struct {
  23. ID int
  24. Address1 string `gorm:"not null;unique"` // Set field as not nullable and unique
  25. Address2 string `gorm:"type:varchar(100);unique"`
  26. Post sql.NullString `gorm:"not null"`
  27. }
  28. type Language struct {
  29. ID int
  30. Name string `gorm:"index:idx_name_code"` // Create index with name, and will create combined index if find other fields defined same name
  31. Code string `gorm:"index:idx_name_code"` // `unique_index` also works
  32. }
  33. type CreditCard struct {
  34. gorm.Model
  35. UserID uint
  36. Number string
  37. }

Conventions

gorm.Model struct

Base model definition gorm.Model, including fields ID, CreatedAt, UpdatedAt, DeletedAt, you could embed it in your model, or only write those fields you want

  1. // Base Model's definition
  2. type Model struct {
  3. ID uint `gorm:"primary_key"`
  4. CreatedAt time.Time
  5. UpdatedAt time.Time
  6. DeletedAt *time.Time
  7. }
  8. // Add fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`
  9. type User struct {
  10. gorm.Model
  11. Name string
  12. }
  13. // Only need field `ID`, `CreatedAt`
  14. type User struct {
  15. ID uint
  16. CreatedAt time.Time
  17. Name string
  18. }

Table name is the pluralized version of struct name

  1. type User struct {} // default table name is `users`
  2. // set User's table name to be `profiles`
  3. func (User) TableName() string {
  4. return "profiles"
  5. }
  6. func (u User) TableName() string {
  7. if u.Role == "admin" {
  8. return "admin_users"
  9. } else {
  10. return "users"
  11. }
  12. }
  13. // Disable table name's pluralization globally
  14. db.SingularTable(true) // if set this to true, `User`'s default table name will be `user`, table name setted with `TableName` won't be affected

Change default tablenames

You can apply any rules on the default table name by defining the DefaultTableNameHandler

  1. gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string {
  2. return "prefix_" + defaultTableName;
  3. }

Column name is the snake case of field’s name

  1. type User struct {
  2. ID uint // column name will be `id`
  3. Name string // column name will be `name`
  4. Birthday time.Time // column name will be `birthday`
  5. CreatedAt time.Time // column name will be `created_at`
  6. }
  7. // Overriding Column Name
  8. type Animal struct {
  9. AnimalId int64 `gorm:"column:beast_id"` // set column name to `beast_id`
  10. Birthday time.Time `gorm:"column:day_of_the_beast"` // set column name to `day_of_the_beast`
  11. Age int64 `gorm:"column:age_of_the_beast"` // set column name to `age_of_the_beast`
  12. }

Field ID as primary key

  1. type User struct {
  2. ID uint // field named `ID` will be the default primary field
  3. Name string
  4. }
  5. // Set a field to be primary field with tag `primary_key`
  6. type Animal struct {
  7. AnimalId int64 `gorm:"primary_key"` // set AnimalId to be primary key
  8. Name string
  9. Age int64
  10. }

Field CreatedAt used to store record’s created time

Create records having CreatedAt field will set it to current time.

  1. db.Create(&user) // will set `CreatedAt` to current time
  2. // To change its value, you could use `Update`
  3. db.Model(&user).Update("CreatedAt", time.Now())

Use UpdatedAt used to store record’s updated time

Save records having UpdatedAt field will set it to current time.

  1. // Whenever one or more `user` fields are edited using Save() or Update(), `UpdatedAt` will be set to current time
  2. db.Save(&user) // will set `UpdatedAt` to current time
  3. db.Model(&user).Update("name", "jinzhu") // will set `UpdatedAt` to current time

Use DeletedAt to store record’s deleted time if field exists

Delete records having DeletedAt field, it won’t be deleted from database, but only set field DeletedAt‘s value to current time, and the record is not findable when querying, refer Soft Delete