Documentation
¶
Index ¶
- Variables
- func AddError(err error) error
- func Assign(attrs ...any) (tx *gorm.DB)
- func Attrs(attrs ...any) (tx *gorm.DB)
- func Begin(opts ...*sql.TxOptions) *gorm.DB
- func Clauses(conds ...clause.Expression) (tx *gorm.DB)
- func Commit() *gorm.DB
- func Connection(fc func(tx *gorm.DB) error) (err error)
- func Count(count *int64) (tx *gorm.DB)
- func Create(value any) (tx *gorm.DB)
- func CreateInBatches(value any, batchSize int) (tx *gorm.DB)
- func DB() (*sql.DB, error)
- func Debug() (tx *gorm.DB)
- func Delete(value any, conds ...any) (tx *gorm.DB)
- func Distinct(args ...any) (tx *gorm.DB)
- func DoMigration() error
- func Exec(sql string, values ...any) (tx *gorm.DB)
- func Find(dest any, conds ...any) (tx *gorm.DB)
- func FindInBatches(dest any, batchSize int, fc func(tx *gorm.DB, batch int) error) *gorm.DB
- func First(dest any, conds ...any) (tx *gorm.DB)
- func FirstOrCreate(dest any, conds ...any) (tx *gorm.DB)
- func FirstOrInit(dest any, conds ...any) (tx *gorm.DB)
- func Get(key string) (any, bool)
- func GetMigrationScript() []string
- func GetModel(name string) *schema.Model
- func Group(name string) (tx *gorm.DB)
- func Having(query any, args ...any) (tx *gorm.DB)
- func InnerJoins(query string, args ...any) (tx *gorm.DB)
- func InstanceGet(key string) (any, bool)
- func InstanceSet(key string, value any) *gorm.DB
- func IsEnabled() bool
- func Joins(query string, args ...any) (tx *gorm.DB)
- func Last(dest any, conds ...any) (tx *gorm.DB)
- func Limit(limit int) (tx *gorm.DB)
- func Model(value any) (tx *gorm.DB)
- func Models() []schema.Model
- func Not(query any, args ...any) (tx *gorm.DB)
- func Offset(offset int) (tx *gorm.DB)
- func Omit(columns ...string) (tx *gorm.DB)
- func Or(query any, args ...any) (tx *gorm.DB)
- func Order(value any) (tx *gorm.DB)
- func Pluck(column string, dest any) (tx *gorm.DB)
- func Preload(query string, args ...any) (tx *gorm.DB)
- func Raw(sql string, values ...any) (tx *gorm.DB)
- func Register(obj *gorm.DB)
- func Rollback() *gorm.DB
- func RollbackTo(name string) *gorm.DB
- func Row() *sql.Row
- func Rows() (*sql.Rows, error)
- func Save(value any) (tx *gorm.DB)
- func SavePoint(name string) *gorm.DB
- func Scan(dest any) (tx *gorm.DB)
- func ScanRows(rows *sql.Rows, dest any) error
- func Scopes(funcs ...func(*gorm.DB) *gorm.DB) (tx *gorm.DB)
- func Select(query any, args ...any) (tx *gorm.DB)
- func Session(config *gorm.Session) *gorm.DB
- func Set(key string, value any) *gorm.DB
- func SetDefaultCharset(charset string)
- func SetDefaultCollation(collation string)
- func SetDefaultEngine(engine string)
- func SetupJoinTable(model any, field string, joinTable any) error
- func Table(name string, args ...any) (tx *gorm.DB)
- func Take(dest any, conds ...any) (tx *gorm.DB)
- func ToSQL(queryFn func(tx *gorm.DB) *gorm.DB) string
- func Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) (err error)
- func Unscoped() (tx *gorm.DB)
- func Update(column string, value any) (tx *gorm.DB)
- func UpdateColumn(column string, value any) (tx *gorm.DB)
- func UpdateColumns(values any) (tx *gorm.DB)
- func Updates(values any) (tx *gorm.DB)
- func Use(plugin gorm.Plugin) error
- func UseModel(models ...any)
- func Where(query any, args ...any) (tx *gorm.DB)
- func WithContext(ctx context.Context) *gorm.DB
Constants ¶
This section is empty.
Variables ¶
var Enabled = false
Functions ¶
func Assign ¶
Assign provide attributes used in FirstOrCreate or FirstOrInit
Assign adds attributes even if the record is found. If using FirstOrCreate, this means that records will be updated even if they are found.
// assign an email regardless of if the record is not found db.Where(User{Name: "non_existing"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user) // user -> User{Name: "non_existing", Email: "fake@fake.org"} // assign email regardless of if record is found db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user) // user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}
func Attrs ¶
Attrs provide attributes used in FirstOrCreate or FirstOrInit
Attrs only adds attributes if the record is not found.
// assign an email if the record is not found db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user) // user -> User{Name: "non_existing", Email: "fake@fake.org"} // assign an email if the record is not found, otherwise ignore provided email db.Where(User{Name: "jinzhu"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user) // user -> User{Name: "jinzhu", Age: 20}
func Clauses ¶
func Clauses(conds ...clause.Expression) (tx *gorm.DB)
Clauses Add clauses
This supports both standard clauses (clause.OrderBy, clause.Limit, clause.Where) and more advanced techniques like specifying lock strength and optimizer hints. See the docs for more depth.
// add a simple limit clause db.Clauses(clause.Limit{Limit: 1}).Find(&User{}) // tell the optimizer to use the `idx_user_name` index db.Clauses(hints.UseIndex("idx_user_name")).Find(&User{}) // specify the lock strength to UPDATE db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)
func Connection ¶
Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is returned to the connection pool.
func CreateInBatches ¶
CreateInBatches inserts value in batches of batchSize
func Delete ¶
Delete deletes value matching given conditions. If value contains primary key it is included in the conditions. If value includes a deleted_at field, then Delete performs a soft delete instead by setting deleted_at with the current time if null.
func Distinct ¶
Distinct specify distinct fields that you want querying
// Select distinct names of users db.Distinct("name").Find(&results) // Select distinct name/age pairs from users db.Distinct("name", "age").Find(&results)
func DoMigration ¶
func DoMigration() error
func FindInBatches ¶
FindInBatches finds all records in batches of batchSize
func FirstOrCreate ¶
FirstOrCreate finds the first matching record, otherwise if not found creates a new instance with given conds. Each conds must be a struct or map.
Using FirstOrCreate in conjunction with Assign will result in an update to the database even if the record exists.
// assign an email if the record is not found result := db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrCreate(&user) // user -> User{Name: "non_existing", Email: "fake@fake.org"} // result.RowsAffected -> 1 // assign email regardless of if record is found result := db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrCreate(&user) // user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"} // result.RowsAffected -> 1
func FirstOrInit ¶
FirstOrInit finds the first matching record, otherwise if not found initializes a new instance with given conds. Each conds must be a struct or map.
FirstOrInit never modifies the database. It is often used with Assign and Attrs.
// assign an email if the record is not found db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user) // user -> User{Name: "non_existing", Email: "fake@fake.org"} // assign email regardless of if record is found db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user) // user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}
func GetMigrationScript ¶
func GetMigrationScript() []string
func Group ¶
Group specify the group method on the find
// Select the sum age of users with given names db.Model(&User{}).Select("name, sum(age) as total").Group("name").Find(&results)
func Having ¶
Having specify HAVING conditions for GROUP BY
// Select the sum age of users with name jinzhu db.Model(&User{}).Select("name, sum(age) as total").Group("name").Having("name = ?", "jinzhu").Find(&result)
func InnerJoins ¶
InnerJoins specify inner joins conditions db.InnerJoins("Account").Find(&user)
func InstanceGet ¶
InstanceGet get value with key from current db instance's context
func InstanceSet ¶
InstanceSet store value with key into current db instance's context
func Joins ¶
Joins specify Joins conditions
db.Joins("Account").Find(&user) db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user) db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{}))
func Limit ¶
Limit specify the number of records to be retrieved
Limit conditions can be cancelled by using `Limit(-1)`.
// retrieve 3 users db.Limit(3).Find(&users) // retrieve 3 users into users1, and all users into users2 db.Limit(3).Find(&users1).Limit(-1).Find(&users2)
func Model ¶
Model specify the model you would like to run db operations
// update all user's name to `hello` db.Model(&User{}).Update("name", "hello") // if user's primary key is non-blank, will use it as condition, then will only update that user's name to `hello` db.Model(&user).Update("name", "hello")
func Not ¶
Not add NOT conditions
Not works similarly to where, and has the same syntax.
// Find the first user with name not equal to jinzhu db.Not("name = ?", "jinzhu").First(&user)
func Offset ¶
Offset specify the number of records to skip before starting to return the records
Offset conditions can be cancelled by using `Offset(-1)`.
// select the third user db.Offset(2).First(&user) // select the first user by cancelling an earlier chained offset db.Offset(5).Offset(-1).First(&user)
func Or ¶
Or add OR conditions
Or is used to chain together queries with an OR.
// Find the first user with name equal to jinzhu or john db.Where("name = ?", "jinzhu").Or("name = ?", "john").First(&user)
func Order ¶
Order specify order when retrieving records from database
db.Order("name DESC") db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})
func Pluck ¶
Pluck queries a single column from a model, returning in the slice dest. E.g.:
var ages []int64 db.Model(&users).Pluck("age", &ages)
func Preload ¶
Preload preload associations with given conditions
// get all users, and preload all non-cancelled orders db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
func RollbackTo ¶
func Save ¶
Save updates value in database. If value doesn't contain a matching primary key, value is inserted.
func Scopes ¶
Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically
func AmountGreaterThan1000(db *gorm.DB) *gorm.DB { return db.Where("amount > ?", 1000) } func OrderStatus(status []string) func *gorm.DB { return func *gorm.DB { return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status) } } db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
func Select ¶
Select specify fields that you want when querying, creating, updating
Use Select when you only want a subset of the fields. By default, GORM will select all fields. Select accepts both string arguments and arrays.
// Select name and age of user using multiple arguments db.Select("name", "age").Find(&users) // Select name and age of user using an array db.Select([]string{"name", "age"}).Find(&users)
func SetDefaultCharset ¶
func SetDefaultCharset(charset string)
func SetDefaultCollation ¶
func SetDefaultCollation(collation string)
func SetDefaultEngine ¶
func SetDefaultEngine(engine string)
func SetupJoinTable ¶
SetupJoinTable setup join table schema
func Table ¶
Table specify the table you would like to run db operations
// Get a user db.Table("users").take(&result)
func Take ¶
Take finds the first record returned by the database in no specified order, matching given conditions conds
func ToSQL ¶
ToSQL for generate SQL string.
db.ToSQL(func(tx *gorm.DB) *gorm.DB { return tx.Model(&User{}).Where(&User{Name: "foo", Age: 20}) .Limit(10).Offset(5) .Order("name ASC") .First(&User{}) })
func Transaction ¶
Transaction start a transaction as a block, return error will rollback, otherwise to commit. Transaction executes an arbitrary number of commands in fc within a transaction. On success the changes are committed; if an error occurs they are rolled back.
func Update ¶
Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields
func UpdateColumns ¶
func Updates ¶
Updates updates attributes using callbacks. values must be a struct or map. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields
func Where ¶
Where add conditions
See the docs for details on the various formats that where clauses can take. By default, where clauses chain with AND.
// Find the first user with name jinzhu db.Where("name = ?", "jinzhu").First(&user) // Find the first user with name jinzhu and age 20 db.Where(&User{Name: "jinzhu", Age: 20}).First(&user) // Find the first user with name jinzhu and age not equal to 20 db.Where("name = ?", "jinzhu").Where("age <> ?", "20").First(&user)
Types ¶
This section is empty.