From bf8a1b337465d77f630636493441efe1b295a23f Mon Sep 17 00:00:00 2001 From: zhangwenjian Date: Fri, 25 Sep 2026 20:00:13 +0800 Subject: [PATCH] =?UTF-8?q?fix=F0=9F=90=9B:=20bind=20the=20generated=20ser?= =?UTF-8?q?vice's=20key=20as=20a=20query=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Get and Update found their row with First(&model, id). GORM reads a string passed that way as a SQL condition rather than a key, so with a string primary key the path parameter went into the WHERE clause as written: "c-1" failed as the expression c - 1, and GET /…/1=1 returned a row. Both now filter on clause.PrimaryColumn with the id as a bound value, which GORM resolves to the model's own quoted key column whatever it is called. Delete keeps Delete(&model, ids): a slice is always taken as key values. --- template/v4/no_actions/service.go.template | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/template/v4/no_actions/service.go.template b/template/v4/no_actions/service.go.template index 9f2a1af7..3be6f66c 100644 --- a/template/v4/no_actions/service.go.template +++ b/template/v4/no_actions/service.go.template @@ -5,6 +5,7 @@ import ( "github.com/go-admin-team/go-admin-core/v2/sdk/service" "gorm.io/gorm" + "gorm.io/gorm/clause" "go-admin/app/{{.PackageName}}/models" "go-admin/app/{{.PackageName}}/service/dto" @@ -37,6 +38,9 @@ func (e *{{.ClassName}}) GetPage(c *dto.{{.ClassName}}GetPageReq, p *actions.Dat } // Get 获取{{.ClassName}}对象 +// +// The key is matched as a value of the model's primary-key column. Handed to +// First on its own, a string key would be read as a SQL condition. func (e *{{.ClassName}}) Get(d *dto.{{.ClassName}}GetReq, p *actions.DataPermission, model *models.{{.ClassName}}) error { var data models.{{.ClassName}} @@ -44,7 +48,8 @@ func (e *{{.ClassName}}) Get(d *dto.{{.ClassName}}GetReq, p *actions.DataPermiss Scopes( actions.Permission(data.TableName(), p), ). - First(model, d.GetId()).Error + Where(clause.Eq{Column: clause.PrimaryColumn, Value: d.GetId()}). + First(model).Error if err != nil && errors.Is(err, gorm.ErrRecordNotFound) { err = errors.New("查看对象不存在或无权查看") e.Log.Errorf("Service Get{{.ClassName}} error:%s \r\n", err) @@ -76,7 +81,9 @@ func (e *{{.ClassName}}) Update(c *dto.{{.ClassName}}UpdateReq, p *actions.DataP var data = models.{{.ClassName}}{} e.Orm.Scopes( actions.Permission(data.TableName(), p), - ).First(&data, c.GetId()) + ). + Where(clause.Eq{Column: clause.PrimaryColumn, Value: c.GetId()}). + First(&data) c.Generate(&data) db := e.Orm.Save(&data)