查询PostgreSQL后GORM的CreatedAt与UpdatedAt日期异常求助
问题原因
你在User结构体中同时嵌入了gorm.Model,又自定义了ID字段,而gorm.Model本身已经包含ID uint、CreatedAt time.Time、UpdatedAt time.Time等核心字段。这种重复定义会导致GORM的字段映射逻辑混乱,无法正确将数据库里的created_at、updated_at值绑定到结构体的对应属性上,最终查询返回的是time.Time类型的零值0001-01-01T00:00:00Z。
解决方案
方案1:移除自定义ID字段,复用gorm.Model自带字段
直接删掉自己定义的ID字段,gorm.Model已经内置了主键ID,如果需要给ID设置json标签,可以在嵌入时调整:
type User struct { gorm.Model `json:"id"` Name string `json:"name" gorm:"not null"` LastName string `json:"last_name" gorm:"not null"` Email string `json:"email" gorm:"not null; unique;"` Password string `json:"password" gorm:"not null"` Bday time.Time `json:"bday" time_format:"sql_datetime" gorm:"nullable"` Gender string `json:"gender" gorm:"nullable"` Address []Address `gorm:"nullable"` Phones []Phone `gorm:"nullable"` OwnedEvents []Event `gorm:"nullable; foreignkey:OwnerID;"` Invites []User `gorm:"nullable; many2many:event_guests;"` Colaborator Colaborator `gorm:"nullable;"` }
方案2:手动声明所有字段,放弃嵌入gorm.Model
如果需要更精细的字段控制,可以完全手动定义所有必要字段,避免嵌入冲突:
type User struct { ID uint `json:"id" gorm:"primary_key"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"` Name string `json:"name" gorm:"not null"` LastName string `json:"last_name" gorm:"not null"` Email string `json:"email" gorm:"not null; unique;"` Password string `json:"password" gorm:"not null"` Bday time.Time `json:"bday" time_format:"sql_datetime" gorm:"nullable"` Gender string `json:"gender" gorm:"nullable"` Address []Address `gorm:"nullable"` Phones []Phone `gorm:"nullable"` OwnedEvents []Event `gorm:"nullable; foreignkey:OwnerID;"` Invites []User `gorm:"nullable; many2many:event_guests;"` Colaborator Colaborator `gorm:"nullable;"` }
验证修改
修改结构体后重新执行查询,GORM就能正确将数据库中的created_at和updated_at值映射到结构体字段,返回正常的时间数据。
内容的提问来源于stack exchange,提问作者Renato N_
相关产品推荐
相关产品推荐

