From 3112896a83ff32230db06b6ae411a6e03a00d2a5 Mon Sep 17 00:00:00 2001 From: zhangwenjian Date: Fri, 25 Sep 2026 20:00:30 +0800 Subject: [PATCH] =?UTF-8?q?fix=F0=9F=90=9B:=20stop=20a=20generated=20Updat?= =?UTF-8?q?e=20when=20its=20row=20is=20not=20found?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update looked its row up and ignored the result. When nothing matched - because the key does not exist, or because the caller's data scope filters the row out - the model stayed at its zero value, Generate copied the request onto it, and Save, finding a zero key, inserted a new row. The update of a row the caller may not see became a row they now own, and the RowsAffected check meant to refuse it never fired, because the insert did affect one. A missing row now ends the update with the same "无权更新该数据" the RowsAffected check returns, and any other lookup error is returned as is. This applies to every generated table, an int id included. --- template/v4/no_actions/service.go.template | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/template/v4/no_actions/service.go.template b/template/v4/no_actions/service.go.template index 3be6f66c..5dc5c4f7 100644 --- a/template/v4/no_actions/service.go.template +++ b/template/v4/no_actions/service.go.template @@ -76,14 +76,25 @@ func (e *{{.ClassName}}) Insert(c *dto.{{.ClassName}}InsertReq) error { } // Update 修改{{.ClassName}}对象 +// +// The row has to be found first. Save on a model whose key is still zero +// inserts, so a row that is missing - or that p filters out - must stop here +// rather than turn the update into a new row. func (e *{{.ClassName}}) Update(c *dto.{{.ClassName}}UpdateReq, p *actions.DataPermission) error { var err error var data = models.{{.ClassName}}{} - e.Orm.Scopes( + err = e.Orm.Scopes( actions.Permission(data.TableName(), p), ). Where(clause.Eq{Column: clause.PrimaryColumn, Value: c.GetId()}). - First(&data) + First(&data).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return errors.New("无权更新该数据") + } + if err != nil { + e.Log.Errorf("{{.ClassName}}Service Update error:%s \r\n", err) + return err + } c.Generate(&data) db := e.Orm.Save(&data)