fix🐛: stop a generated Update when its row is not found

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.
This commit is contained in:
zhangwenjian
2026-09-25 20:00:30 +08:00
parent bf8a1b3374
commit 3112896a83
+13 -2
View File
@@ -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)