Create Record
user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()} |
Create With Selected Fields
Create with selected fields
db.Select("Name", "Age", "CreatedAt").Create(&user) |
Create without selected fields
db.Omit("Name", "Age", "CreatedAt").Create(&user) |
Create Hooks
GORM allows hooks BeforeSave
, BeforeCreate
, AfterSave
, AfterCreate
, those methods will be called when creating a record, refer Hooks for details
func (u *User) BeforeCreate(tx *gorm.DB) (err error) { |
Batch Insert
Pass slice data to method Create
, GORM will generate a single SQL statement to insert all the data and backfill primary key values, hook methods will be invoked too.
var users = []User{{Name: "jinzhu1"}, {Name: "jinzhu2"}, {Name: "jinzhu3"}} |
Batch Insert is also supported when using Upsert and Create With Associations
Create From Map
GORM supports create from map[string]interface{}
and []map[string]interface{}{}
, e.g:
DB.Model(&User{}).Create(map[string]interface{}{ |
NOTE When creating from map, hooks won’t be invoked, associations won’t be saved and primary key values won’t be back filled
Create From SQL Expr/Context Valuer
GORM allows insert data with SQL expression, there are two ways to achieve this goal, create from map[string]interface{}
or Customized Data Types, for example:
// Create from map |
Advanced
Create With Associations
When creating some data with associations, if its associations value is not zero-value, those associations will be upserted, and its Hooks
methods will be invoked.
type CreditCard struct { |
You can skip saving associations with Select
, Omit
, for example:
db.Omit("CreditCard").Create(&user) |
Default Values
You can define default values for fields with tag default
, for example:
type User struct { |
Then the default value will be used when inserting into the database for zero-value fields
NOTE Any zero value like 0
, ''
, false
won’t be saved into the database for those fields defined default value, you might want to use pointer type or Scanner/Valuer to avoid this, for example:
type User struct { |
NOTE You have to setup the default
tag for fields having default value in databae or GORM will use the zero value of the field when creating, for example:
type User struct { |
Upsert / On Conflict
GORM provides compatible Upsert support for different databases
import "gorm.io/gorm/clause" |
Also checkout FirstOrInit
, FirstOrCreate
on Advanced Query
Checkout Raw SQL and SQL Builder for more details