🐛 fix(model): preserve created_time on Model update and streamline field maintenance
The update operation for Model previously overwrote `created_time` with zero
because GORM included every struct field in the UPDATE statement.
This commit adjusts `Model.Update()` to:
* Call `Omit("created_time")` so the creation timestamp is never modified.
* Refresh `UpdatedTime` with `common.GetTimestamp()` before persisting.
* Delegate the remainder of the struct to GORM, eliminating the need to
maintain an explicit allow-list whenever new fields are introduced.
No API contract is changed; existing CRUD endpoints continue to work
normally while data integrity for historical records is now guaranteed.
This commit is contained in:
@@ -50,8 +50,11 @@ func (mi *Model) Insert() error {
|
||||
|
||||
// Update 更新现有模型记录
|
||||
func (mi *Model) Update() error {
|
||||
// 仅更新需要变更的字段,避免覆盖 CreatedTime
|
||||
mi.UpdatedTime = common.GetTimestamp()
|
||||
return DB.Save(mi).Error
|
||||
|
||||
// 排除 created_time,其余字段自动更新,避免新增字段时需要维护列表
|
||||
return DB.Model(&Model{}).Where("id = ?", mi.Id).Omit("created_time").Updates(mi).Error
|
||||
}
|
||||
|
||||
// Delete 软删除模型记录
|
||||
|
||||
Reference in New Issue
Block a user