首页 > 后端开发 > Golang > 正文

Gorm 中的更新将created_at、updated_at 作为默认时间

王林
发布: 2024-02-05 23:21:03
转载
1226 人浏览过

Gorm 中的更新将created_at、updated_at 作为默认时间

问题内容

我正在尝试使用 gorm 更新数据库中的实体帖子,更新在数据库中正确反映,但在 gorm 包返回的对象中,created_at 和 Updated_at 字段是默认时间,即“0001/01/01 ...” p>

我的数据库模型是

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;"`
}
登录后复制

查询是

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
}
登录后复制

仅供参考,API 响应是 -

{
    "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"
    }
}
登录后复制


正确答案


您应该尝试在更新记录时手动设置 UpdatedAt 字段。像这样的事情:

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
}
登录后复制

以上是Gorm 中的更新将created_at、updated_at 作为默认时间的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!