Gorm uses specifications and best practices for reference only

logger

Logger should be enabled to print all SQL by default in the development environment or locally to track SQL execution:

if os.Getenv("env") = ="local" {
    db.LogMode(true)}Copy the code

To share code

The example of the official website is very good, directly copied here to use:

func Paginate(r *http.Request) func(db *gorm.DB) *gorm.DB {
  return func (db *gorm.DB) *gorm.DB {
    page, _ := strconv.Atoi(r.Query("page"))
    if page == 0 {
      page = 1
    }

    pageSize, _ := strconv.Atoi(r.Query("page_size"))
    switch {
    case pageSize > 100:
      pageSize = 100
    case pageSize <= 0:
      pageSize = 10
    }

    offset := (page - 1) * pageSize
    return db.Offset(offset).Limit(pageSize)
  }
}

db.Scopes(Paginate(r)).Find(&users)
db.Scopes(Paginate(r)).Find(&articles)
Copy the code

The default value

Use the default field to specify a field default value:


type User struct {
  ID   int64
  Name string `gorm:"default:galeone"`
  Age  int64  `gorm:"default:18"`
}
Copy the code

For GOLang, the default structure field has a zero value, while GORM ignores zero updates by default. Because zero values are ignored when struct is converted to map. If you want to update a zero-value field, you can use the save method, or you can use map. Pointers can also be used for personal recommendations, for example:

var isTeacher *bool // Defaults to nil, which can be updated after assignment
Copy the code

other

Pluck: Use Pluck to query a single column from the database and scan it into a slice. Note that Pluck produces an SQL injection

Resolver: Random policy is adopted for databases with multiple copies

Data type: Uint8 is recommended to be converted to INT8 when serializing because byte is essentially uint8

Read/write separation: Except for the default SELECT, all SQL executions are executed in the master library by default

One final question: in a read-write separated database, do read executions with transactions default to using the database’s master library for reads?