我正在尝试使用 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中文网其他相关文章!