Create record
You can insert a record using the type-safe Create method, which only accepts pointer of current model when creating data
// u refer to query.user |
Create record with selected fields
You can use Select when creating data, it will only insert those selected fields
u := query.User |
ignore fields with Omit
u := query.User |
Batch Insert
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.
var users = []*model.User{{Name: "modi"}, {Name: "zhangqiang"}, {Name: "songyuan"}} |
You can specify batch size when creating with CreateInBatches, e.g:
var users = []*model.User{{Name: "modi_1"}, /*...*/, {Name: "modi_10000"}} |
It will works if you set CreateBatchSize in gorm.Config / gorm.Session
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ |
Upsert / On Conflict
Gen provides compatible Upsert support for different databases
import "gorm.io/gorm/clause" |
NOTE
Clausespasses its arguments through Gen’s clause security check.clause.OnConflict.DoUpdatesvalues must not begorm.Expr— such assignments
are rejected with “OnConflict clause assignment with gorm.Expr is banned for
security reasons for now”. See Clauses.
Save
Save is an upsert: it inserts the records and, on primary-key conflict, updates
all columns. Unlike GORM’s Save (which runs an UPDATE when the primary key
is set), the generated Save always executesClauses(clause.OnConflict{UpdateAll: true}).Create(values) — a record with a set
primary key is still INSERTed, and the conflict turns it into a full-column update:
u := query.Use(db).User |
See Clauses for the security check that applies to theOnConflict clause.
Returning
On databases that support it (PostgreSQL, SQL Server; SQLite >= 3.35), Returning
appends a RETURNING clause to write statements and passes the destination
you provide to the driver:
u := query.Use(db).User |
For queries, GORM does not emit RETURNING (it is a write-statement clause),
so First/Take/Last run a plain SELECT — but they scan into the
destination given to Returning when one is set, instead of allocating their
own result. Find always allocates its own result slice and ignores theReturning destination.