Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于在BeforeUpdate钩子函数中执行变更字段的问题 #7170

Open
master-nan opened this issue Aug 26, 2024 · 0 comments
Open

关于在BeforeUpdate钩子函数中执行变更字段的问题 #7170

master-nan opened this issue Aug 26, 2024 · 0 comments
Assignees
Labels
type:question general questions

Comments

@master-nan
Copy link

Your Question

我在BeforeUpdate钩子函数中有个需求想统一变更修改人字段,于是使用tx.Statement.SetColumn("modify_user", xxx)设置,但是出现了问题

The document you expected this should be explained

追踪了代码发现我调用Updates更新时传入的结构体是精简后的模型,不是表对应的结构体,那他会从Statement下的Model中获取下标,然后去Dest中找这个字段,这可能引发错误,因为我传入的修改结构体可能只是部分字段;当然了如果传入Updates的是map[string]interface{}并不存在这个问题

Expected answer

                    destValue := reflect.ValueOf(stmt.Dest)
		for destValue.Kind() == reflect.Ptr {
			destValue = destValue.Elem()
		}

		if stmt.ReflectValue != destValue {
			if !destValue.CanAddr() {
				destValueCanAddr := reflect.New(destValue.Type())
				destValueCanAddr.Elem().Set(destValue)
				stmt.Dest = destValueCanAddr.Interface()
				destValue = destValueCanAddr.Elem()
			}

			switch destValue.Kind() {
			case reflect.Struct:
				stmt.AddError(field.Set(stmt.Context, destValue, value))
			default:
				stmt.AddError(ErrInvalidData)
			}
		}
		这里的destValue 是不是应该从stmt.Model中得到
                     destValue := reflect.ValueOf(stmt.Model)
@master-nan master-nan added the type:question general questions label Aug 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

3 participants
@jinzhu @master-nan and others