英文:
How to add value before create using gorm?
问题
我有这个post.go模型
package models
type Post struct {
	Id             uint   `json:"ID"`
	Name           string   `json:"Name"`
	Message        string `gorm:"type:text; index" json:"Message"`
	Status         string `gorm:"type:varchar(255); index" json:"Status"`
	Desc           string `gorm:"type:text; index" json:"Desc"`
}
func (p *Post) BeforeCreate() (err error) {
	p.Status = "todo"
	return nil
}
我需要在创建任何记录时,默认将状态设置为todo值
在我的控制器中:
config.DB.Model(&models.Post{}).Create(&posts)
结果是我在数据库中得到了一个空值的状态。
英文:
I have this post.go model
package models
type Post struct {
	Id             uint   `json:"ID"`
	Name           string   `json:"Name"`
	Message        string `gorm:"type:text; index" json:"Message"`
	Status         string `gorm:"type:varchar(255); index" json:"Status"`
	Desc           string `gorm:"type:text; index" json:"Desc"`
}
func (p *Post) BeforeCreate() (err error) {
	p.Status = "todo"
	return nil
}
I need when I create any record by default put the status into the todo value
in my controller:
config.DB.Model(&models.Post{}).Create(&posts)
The result is I got a null value in status in the database
答案1
得分: 0
BeforeCreate接口的签名是错误的,应该是BeforeCreate(*gorm.DB) error。
func (p *Post) BeforeCreate(tx *gorm.DB) (err error) {
    p.Status = "todo"
    return nil
}
另一种方法是向Post结构体添加default-values。
type Post struct {
    Id             uint   `json:"ID"`
    Name           string `json:"Name"`
    Message        string `gorm:"type:text; index" json:"Message"`
    Status         string `gorm:"type:varchar(255); index; default: todo" json:"Status"`
    Desc           string `gorm:"type:text; index" json:"Desc"`
}
输出:
db.Create(&Post{}) // INSERT INTO `posts` (`name`,`message`,`status`,`desc`) VALUES ("","","todo","") RETURNING `id`
英文:
BeforeCreate interface signature is incorrect it should be BeforeCreate(*gorm.DB) error
func (p *Post) BeforeCreate(tx *gorm.DB) (err error) {
    p.Status = "todo"
    return nil
}
Another way would be to add default-values to the post struct
type Post struct {
    Id             uint   `json:"ID"`
    Name           string `json:"Name"`
    Message        string `gorm:"type:text; index" json:"Message"`
    Status         string `gorm:"type:varchar(255); index; default: todo" json:"Status"`
    Desc           string `gorm:"type:text; index" json:"Desc"`
}
Output:
db.Create(&Post{}) // INSERT INTO `posts` (`name`,`message`,`status`,`desc`) VALUES ("","","todo","") RETURNING `id`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论