SoFunction
Updated on 2025-03-03

Example of definition of golang Gorm model structure

1. Model

1.1. Model definition

type User struct {
    
    Birthday     
    Age          int
    Name         string  `gorm:"size:255"`       // The default length of string is 255, use this tag to reset.    Num          int     `gorm:"AUTO_INCREMENT"` // Self-increase    CreditCard        CreditCard      // One-To-One (has a UserID of the CreditCard table as a foreign key)    Emails            []Email         // One-To-Many (Have multiple - UserID of the Email table as a foreign key    BillingAddress    Address         // One-To-One (belongs to - the BillingAddressID of this table as a foreign key)    BillingAddressID  sql.NullInt64
    ShippingAddress   Address         // One-To-One (belongs to - ShippingAddressID of this table as a foreign key)    ShippingAddressID int
    IgnoreMe          int `gorm:"-"`   // Ignore this field    Languages         []Language `gorm:"many2many:user_languages;"` // Many-To-Many, 'user_languages' is the connection table}
type Email struct {
    ID      int
    UserID  int     `gorm:"index"` // Foreign key (belongs to), tag `index` is to create an index for this column    Email   string  `gorm:"type:varchar(100);unique_index"` // `type` sets the sql type, `unique_index` sets a unique index for this column    Subscribed bool
}
type Address struct {
    ID       int
    Address1 string         `gorm:"not null;unique"` // Set the field to non-empty and unique    Address2 string         `gorm:"type:varchar(100);unique"`
    Post      `gorm:"not null"`
}
type Language struct {
    ID   int
    Name string `gorm:"index:idx_name_code"` // Create an index and name it. If you find another index with the same name, create a composite index    Code string `gorm:"index:idx_name_code"` // `unique_index` also works
}
type CreditCard struct {
    
    UserID  uint
    Number  string
}

2. Agreement

2.1. Structure

Basic model definition, including fieldsIDCreatedAtUpdatedAtDeletedAt, you can embed it into your model, or just write the fields you want

// Definition of basic modeltype Model struct {
  ID        uint `gorm:"primary_key"`
  CreatedAt 
  UpdatedAt 
  DeletedAt *
}
// Add fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`type User struct {
  
  Name string
}
// Only fields `ID`, `CreatedAt` are requiredtype User struct {
  ID        uint
  CreatedAt 
  Name      string
}

2.2. Table name is a plural form of the structure name

type User struct {} // The default table name is `users`// Set the User's table name to `profiles`func (User) TableName() string {
  return "profiles"
}
func (u User) TableName() string {
    if  == "admin" {
        return "admin_users"
    } else {
        return "users"
    }
}
// Globally disable table name plural(true) // If set to true, the default table name of `User` is `user`, the table name set using `TableName` will not be affected

2.3. Change the default table name

You can defineDefaultTableNameHandlerApply any rules to the default table name.

 = func (db *, defaultTableName string) string  {
    return "prefix_" + defaultTableName;
}

2.4. Column name is the serpentine lowercase of the field name

type User struct {
  ID uint             // Column name is `id`  Name string         // Column name `name`  Birthday   // The column is named `birthday`  CreatedAt  // The column name is `created_at`}
// Reset the column nametype Animal struct {
    AnimalId    int64     `gorm:"column:beast_id"`         // Set the column name to `beast_id`    Birthday     `gorm:"column:day_of_the_beast"` // Set the column name to `day_of_the_beast`    Age         int64     `gorm:"column:age_of_the_beast"` // Set the column name to `age_of_the_beast`}

2.5. Field ID is the primary key

type User struct {
  ID   uint  // Field `ID` is the default primary key  Name string
}
// Use tag `primary_key` to set the primary keytype Animal struct {
  AnimalId int64 `gorm:"primary_key"` // Set AnimalId as the primary key  Name     string
  Age      int64
}

2.6. Field CreatedAt is used to store the creation time of the record

Create aCreatedAtThe record of the field will be set to the current time

(&user) // `CreatedAt` will be set to the current time// To change its value, you need to use `Update`(&user).Update("CreatedAt", ())

2.7. Field UpdateAt is used to store the record's modification time

Save withUpdatedAtThe record of the field will be set to the current time

(&user) // `UpdatedAt` will be set to the current time(&user).Update("name", "jinzhu") // `UpdatedAt` will be set to the current time

2.8. Field DeletedAt is used to store the deletion time of the record, if the field exists

Delete withDeletedAtRecords of fields, it will not flush the database, but only fields will beDeletedAtSet to the current time and the record cannot be found during query, see [Soft Delete]

The above is the detailed content of the definition example of the golang gorm model structure. For more information about golang gorm model structure, please pay attention to my other related articles!