How to add value before create using gorm?

Issue

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

Solution

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`

Answered By – Chandan

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.