Insert Query Builder
The insert query builder lets you insert rows into tables without using models. Use it for bulk inserts, raw table inserts, or when you need to bypass model hooks and timestamps.
Overview
Nimbus uses GORM's Table().Create() for inserts. You can insert a single map, a struct, or a slice for bulk inserts.
Single insert
// Insert as map (column names as keys)
db := database.Get()
result := db.Table("posts").Create(map[string]any{
"title": "Hello World",
"content": "First post content",
"status": "draft",
"created_at": time.Now(),
"updated_at": time.Now(),
})
// Insert returns the number of rows affected
if result.Error != nil {
return result.Error
}
Bulk insert
Pass a slice of maps or structs to insert multiple rows in one query.
rows := []map[string]any{
{"title": "Post 1", "content": "Content 1", "status": "draft"},
{"title": "Post 2", "content": "Content 2", "status": "draft"},
}
db.Table("posts").Create(rows)
Insert with model
For models, use db.Create(&model). GORM auto-sets timestamps and runs hooks.
post := Post{Title: "Hello", Content: "World", Status: "draft"}
db.Create(&post)
// post.ID is set after insert
Create in batches
Use CreateInBatches for large inserts to avoid memory issues.
db.CreateInBatches(rows, 100)
Returning inserted ID
When using a struct, GORM scans the generated ID back into the struct. For maps, use a model with a pointer or scan the result.
post := Post{Title: "New", Content: "Post"}
db.Create(&post)
fmt.Println(post.ID) // auto-populated