在使用gorm之前如何添加值?

huangapple go评论76阅读模式
英文:

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`

huangapple
  • 本文由 发表于 2022年5月26日 06:50:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/72384903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定