Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Gorm is the developer-friendly Golang ORM library.
The characteristics of
  • Full-feature ORM (almost all features)
  • Model association (one-to-one, one-to-many, one-to-many (reverse), many-to-many, polymorphic association)
  • Hook (Before/After the Create/Save/Update/Delete/Find)
  • preload
  • The transaction
  • Composite primary key
  • The SQL builder
  • Automatic migration
  • The log
  • Write extensible plug-ins based on GORM callbacks
  • Full feature test coverage
  • Developer friendly
The installation
go get -u github.com/jinzhu/gorm
Copy the code

Example:

package main

import (
  "github.com/jinzhu/gorm"
  _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Product struct {
  gorm.Model
  Code string
  Price uint
}

func main(a) {
  db, err := gorm.Open("sqlite3"."test.db")
  iferr ! =nil {
    panic("failed to connect database")}defer db.Close()

  // Automatically check whether the structure of the Product has changed, and then migrate
  db.AutoMigrate(&Product{})

  / / to add
  db.Create(&Product{Code: "L1212", Price: 1000})

  / / check
  var product Product
  db.First(&product, 1) // Find the product with id 1
  db.First(&product, "code = ?"."L1212") // find the product with code L1212

  // The price of the updated product is 2000
  db.Model(&product).Update("Price".2000)

  // Delete - delete the product
  db.Delete(&product)
}
Copy the code
model

Models are typically generic Golang constructs, Go primitive data types, or Pointers. Sql. Scanner and driver.Valuer, as well as interfaces.

Example:

type User struct {
  gorm.Model
  Name         string
  Age          sql.NullInt64
  Birthday     *time.Time
  Email        string  `gorm:"type:varchar(100); unique_index"`
  Role         string  `gorm:"size:255"` // Set the field size to 255 bytes
  MemberNumber *string `gorm:"unique; not null"` // Set the memberNumber field to be unique and not empty
  Num          int     `gorm:"AUTO_INCREMENT"` // Set the Num field to autoincrement
  Address      string  `gorm:"index:addr"` // create an index for Address with the name 'addr'
  IgnoreMe     int     `gorm:"-"` // Ignore this field
}
Copy the code
Structure of the label

A label is an optional tag when declaring a model. GORM supports the following tags:

Supported structure tags
The label instructions
Column Specify the column name
Type Specifies the type of column
Size Specifies the size of the column. The default is 255
PRIMARY_KEY Specify a column as the primary key
UNIQUE Specify a unique column
DEFAULT Specify a default value for a column
PRECISION Specifies the precision of the data for the column
NOT NULL Specifies that the column data is not null
AUTO_INCREMENT Specifies whether data for a column is self-incremented
INDEX Create an index with or without a name, and create a composite index with the same name
UNIQUE_INDEX similarThe indexCreate a unique index
EMBEDDED Set struct to Embedded
EMBEDDED_PREFIX Sets the prefix name of the embedded structure
Ignore those fields
Associated structure tag

For more information, see the Association section

The label instructions
MANY2MANY Specify the join table name
FOREIGNKEY Specifies the foreign key
ASSOCIATION_FOREIGNKEY Specifies the associated foreign key
POLYMORPHIC Specifies the polymorphic type
POLYMORPHIC_VALUE Specifies the value of a polymorphism
JOINTABLE_FOREIGNKEY Specifies the foreign key for the join table
ASSOCIATION_JOINTABLE_FOREIGNKEY Specifies the associated foreign key for the join table
SAVE_ASSOCIATIONS Whether to automatically save the association
ASSOCIATION_AUTOUPDATE Whether to update the association automatically
ASSOCIATION_AUTOCREATE Whether to automatically create an association
ASSOCIATION_SAVE_REFERENCE Whether to reference the auto-saved association
PRELOAD Whether to automatically preload the association

practice

gorm.Model

Gorm.Model is a structure that contains basic fields such as ID, CreatedAt, UpdatedAt, and DeletedAt.

You can use it to embed it in your model, or you can use it to build your own model.

/ / gorm. Model definition
type Model struct {
  ID        uint `gorm:"primary_key"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt *time.Time
}

// Inject fields' ID ', 'CreatedAt', 'UpdatedAt', and 'DeletedAt' into the 'User' model
type User struct {
  gorm.Model
  Name string
}

// Declare the gorm.model Model
type User struct {
  ID   int
  Name string
}
Copy the code

ID is the primary key

By default, GORM uses ID as the primary key.

type User struct {
  ID   string // The field name 'ID' will be used as the default primary key
}

// Set field 'AnimalID' as default primary key
type Animal struct {
  AnimalID int64 `gorm:"primary_key"`
  Name     string
  Age      int64
}
Copy the code

The plural table name

The table name is the plural form of the structure name

type User struct {} // The default table name is' users'

// Set the table name of 'User' to 'profiles'
func (User) TableName(a) string {
  return "profiles"
}

func (u User) TableName(a) string {
    if u.Role == "admin" {
        return "admin_users"
    } else {
        return "users"}}// If the plural attribute is set to true, the name of the table 'User' will be 'User'
db.SingularTable(true)
Copy the code

Specifies the name of the table

// Create the 'delete_users' table with the' User 'structure
db.Table("deleted_users").CreateTable(&User{})

var deleted_users []User
db.Table("deleted_users").Find(&deleted_users)
//// SELECT * FROM deleted_users;

db.Table("deleted_users").Where("name = ?"."jinzhu").Delete()
//// DELETE FROM deleted_users WHERE name = 'jinzhu';
Copy the code

Change the default table name

You can use any rules for table names by defining the DefaultTableNameHandler field.

gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string  {
    return "prefix_" + defaultTableName;
}
Copy the code

Serpentine column names

The column name is the serpentine lowercase form of the field name

type User struct {
  ID        uint      // The field name is' id '
  Name      string    // The field name is' name '
  Birthday  time.Time // The field name is' birthday '
  CreatedAt time.Time // The field name is' created_at '
}

// Rewrite the column name
type Animal struct {
    AnimalId    int64     `gorm:"column:beast_id"`         // Set the column name to 'beast_id'
    Birthday    time.Time `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'
}
Copy the code

Timestamp tracking

CreatedAt

For a model with a CreatedAt field, it will be set to the current time when the record was first created.

db.Create(&user) // 'CreatedAt' is set to the current time

// You can use the 'Update' method to change the default time
db.Model(&user).Update("CreatedAt", time.Now())
Copy the code

UpdatedAt

For models that have an UpdatedAt field, it will be set to record the current time when updates are made.

db.Save(&user) // Set 'UpdatedAt' to the current time

db.Model(&user).Update("name"."jinzhu") // Set 'UpdatedAt' to the current time
Copy the code

DeletedAt

For models with DeletedAt fields, when instances of them are deleted, they are not deleted from the database, but the DeletedAt field is set to the current time.