SoFunction
Updated on 2025-03-04

Golang Gorm update log execution SQL example detailed explanation

1. Update log

1.1. v1.0

1.1.1. Destructive Changes

  • The return type is*Instead
  • Updates will only update the changed fields

Most applications will not be affected only if you change the updated value in the callback (e.g.BeforeSaveBeforeUpdate) should be used,For example:

func (user *User) BeforeUpdate(scope *) {
  if pw, err := (, 0); err == nil {
    ("EncryptedPassword", pw)
    // = pw // Not working, the EncryptedPassword field will not be included when updating  }
}

Soft-deletion's default query scope will only checkdeleted_at IS NULL

Before it checks that deleted_at is less than 0001-01-02 also excludes blank time, such as:

SELECT * FROM users WHERE deleted_at IS NULL OR deleted_at <= '0001-01-02'

But it's not necessary, if you use*As a modelDeletedAt, it has beenUsed, so SQL is enough

SELECT * FROM users WHERE deleted_at IS NULL

So if you useThen you are OK and nothing needs to be changed, just make sure all records have blank timedeleted_atSet asNULL, sample migration script:

import (
    "/jinzhu/now"
)
func main() {
  var models = []interface{}{&User{}, &Image{}}
  for _, model := range models {
    ().Model(model).Where("deleted_at < ?", ("0001-01-02")).Update("deleted_at", ("NULL"))
  }
}
  • New ToDBName logic

Before GORM converts the name of struct, Field to the db name, only those fromgolintCommon initializations (e.g.HTTPURI) is specially treated.

So fieldsHTTPThe database name will behttpInsteadh_t_t_p, but some other initializations, such asSKUNot in golint, its database name will bes_k_u, which looks ugly, this version fixes this, any capital initialization should be converted correctly.

mistakeRecordNotFoundRenamed toErrRecordNotFound

mssqlThe driver has been removed from the default driver.

Import it with import _ "/jinzhu/gorm/dialects/mssql"

Hstore has been moved to /jinzhu/gorm/dialects/postgres

GORM executes sql

type Object interface {
  GroupOrderOpenlog() (uidList []int)
}
func (o *object) GroupOrderOpenlog() {
	type res struct {
		Uid int `json:"uid"`
	}
	var re []res
	sql:= "SELECT uid FROM order_openlog  GROUP BY uid"
	(sql).Scan(&amp;re)
	(re)
	for _,k :=range re{
		()
	}
}

The above is the detailed explanation of the example of golang gorm update log execution SQL. For more information about golang gorm update log execution SQL, please follow my other related articles!