Your Question
My question is that why when I create a new object why default values aren't used in object creation?
// Todo model
type Todo struct {
ID uint `gorm:"primarykey" json:"id"`
Title string `gorm:"size:100" json:"title"`
Status string `gorm:"size:20,default:Created,index" json:"status"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"createdAt"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updatedAt"`
}
// Here is the create query
todo := db.Todo{Title: "Some title"}
result := m.App.DB.Create(&todo)
fmt.Println(todo.Status)
// Output:
// nothing (empty string)
I have also tried below query but I still get the same results:
m.App.DB.Select("Title").Create(&todo)
Expected answer
Set default value for structs before creating.
fmt.Println(todo.Status)
// Output:
// Created
Comment From: Heliner
same as this issue https://github.com/go-gorm/gorm/issues/5146 if you need the defeault values , define mode like this
// Todo model
type Todo struct {
ID *uint `gorm:"primarykey" json:"id"`
Title *string `gorm:"size:100" json:"title"`
Status *string `gorm:"size:20,default:Created,index" json:"status"`
CreatedAt *time.Time `gorm:"autoCreateTime" json:"createdAt"`
UpdatedAt *time.Time `gorm:"autoUpdateTime" json:"updatedAt"`
}
Comment From: a631807682
The tag separator is ; not ,
type Todo struct {
...
Status string `gorm:"size:20;default:Created;index" json:"status"`
}
Comment From: mojixcoder
if you need the default values , define mode like this
I don't think it's the problem. look at this model in the docs:
type User struct {
ID int64
Name string `gorm:"default:galeone"`
Age int64 `gorm:"default:18"`
}
Comment From: mojixcoder
Thanks, tag separator was the problem. @a631807682