创建记录
user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()} |
我们还可以使用 Create()
创建多项记录:
users := []*User{ |
用指定的字段创建记录
创建记录并为指定的字段分配值:
db.Select("Name", "Age", "CreatedAt").Create(&user) |
创建记录并忽略要省略的传递字段的值:
db.Omit("Name", "Age", "CreatedAt").Create(&user) |
批量插入
To efficiently insert large number of records, pass a slice to the Create
method. GORM will generate a single SQL statement to insert all the data and backfill primary key values, hook methods will be invoked too. It will begin a transaction when records can be splited into multiple batches.
var users = []User{{Name: "jinzhu1"}, {Name: "jinzhu2"}, {Name: "jinzhu3"}} |
You can specify batch size when creating with CreateInBatches
, e.g:
var users = []User{{Name: "jinzhu_1"}, ...., {Name: "jinzhu_10000"}} |
Batch Insert is also supported when using Upsert and Create With Associations
NOTE initialize GORM with
CreateBatchSize
option, allINSERT
will respect this option when creating record & associations
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ |
创建钩子
GORM allows user defined hooks to be implemented for BeforeSave
, BeforeCreate
, AfterSave
, AfterCreate
. These hook method will be called when creating a record, refer Hooks for details on the lifecycle
func (u *User) BeforeCreate(tx *gorm.DB) (err error) { |
If you want to skip Hooks
methods, you can use the SkipHooks
session mode, for example:
DB.Session(&gorm.Session{SkipHooks: true}).Create(&user) |
根据 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
使用 SQL 表达式、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 |
高级选项
关联创建
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) |
默认值
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 or virtual/generated value in database, if you want to skip a default value definition when migrating, you could usedefault:(-)
, for example:
type User struct { |
When using virtual/generated value, you might need to disable its creating/updating permission, check out Field-Level Permission
Upsert 及冲突
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