Search code examples
postgresqlgogo-gorm

Update in Gorm gives created_at, updated_at as default time


I am trying to update a entity post in db using gorm, the update reflects properly in db but in object returned by gorm package the created_at and updated_at fields are default times i.e '0001/01/01 ...'

my db models are

type Base struct {
    ID        uuid.UUID       `json:"id" gorm:"primaryKey;default:gen_random_uuid();not null"`
    CreatedAt time.Time       `json:"created_at" gorm:"default:now()"`
    UpdatedAt time.Time       `json:"updated_at" gorm:"default:now()"`
    DeletedAt *gorm.DeletedAt `gorm:"index" json:"deleted_at" swaggertype:"primitive,string"`
}



type Post struct {
    Base
    Title       string    `json:"title" gorm:"column:title"`
    TLDR        string    `json:"tldr" gorm:"column:tldr"`
    HTML        string    `json:"html" gorm:"column:html"`
    JSON        string    `json:"json" gorm:"column:json"`
    BannerImage string    `json:"banner_image" gorm:"column:banner_image"`
    Slug        string    `json:"slug" gorm:"column:slug"`
    Status      Status    `json:"status" gorm:"column:status"`
    AuthorID    uuid.UUID `json:"author_id" gorm:"column:author_id;"`
}

the query is

func (p *pgPostRepository) UpdatePost(postDetails *models.Post) (*models.Post, error) {
    db := p.db.GetClient().(*gorm.DB)
    err := db.Model(&models.Post{}).Where(&models.Post{
        Base: models.Base{
            ID: postDetails.ID,
        },
    }).Updates(&postDetails).Error
    if err != nil {
        return nil, err
    }
    return postDetails, nil
}

FYI the API response is -

{
    "message": "post updated successfully",
    "post": {
        "id": "e4645d79-51da-4e08-85d3-e7409ad6b77b",
        "created_at": "0001-01-01T00:00:00Z",
        "updated_at": "0001-01-01T00:00:00Z",
        "deleted_at": null,
        "title": "Sample Title",
        "tldr": "Brief summary of the content",
        "html": "<p>This is the HTML content.</p>",
        "json": "{\"key\": \"value\"}",
        "banner_image": "https://example.com/image.jpg",
        "slug": "sample-title-1694539437151872840",
        "status": "draft",
        "author_id": "96fa719c-358e-4c5d-b878-daee02e2c38b"
    }
}

Solution

  • You should try to set the UpdatedAt field manually while updating the record. Something like this:

    func (p *pgPostRepository) UpdatePost(postDetails *models.Post) (*models.Post, error) {
        db := p.db.GetClient().(*gorm.DB)
    
        postDetails.UpdatedAt = time.Now()
    
        err := db.Model(&models.Post{}).Where(&models.Post{
            Base: models.Base{
                ID: postDetails.ID,
            },
        }).Updates(&postDetails).Error
    
        if err != nil {
            return nil, err
        }
        
        return postDetails, nil
    }