From eb42eb6f27c40b117240b69ab34c628d23166825 Mon Sep 17 00:00:00 2001 From: t0ng7u Date: Fri, 1 Aug 2025 02:21:14 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(model):=20preserve=20created?= =?UTF-8?q?=5Ftime=20on=20Model=20update=20and=20streamline=20field=20main?= =?UTF-8?q?tenance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- model/model_meta.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/model/model_meta.go b/model/model_meta.go index ef5e883a..6f6c5e22 100644 --- a/model/model_meta.go +++ b/model/model_meta.go @@ -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 软删除模型记录