From 7c2ecdfc1c738f118b892d593ac3899d8e92b74b Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 30 Jul 2020 10:23:35 +0800 Subject: [PATCH] Fix use pointer of Valuer as foreign key, close #3212 --- schema/field.go | 5 +++-- tests/scanner_valuer_test.go | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/schema/field.go b/schema/field.go index f377a34a..329ae41c 100644 --- a/schema/field.go +++ b/schema/field.go @@ -742,15 +742,16 @@ func (field *Field) setupValuerAndSetter() { } else if _, ok := fieldValue.Elem().Interface().(sql.Scanner); ok { // pointer scanner field.Set = func(value reflect.Value, v interface{}) (err error) { + reflectV := reflect.ValueOf(v) + if valuer, ok := v.(driver.Valuer); ok { - if valuer == nil { + if valuer == nil || reflectV.IsNil() { field.ReflectValueOf(value).Set(reflect.New(field.FieldType).Elem()) } else { v, _ = valuer.Value() } } - reflectV := reflect.ValueOf(v) if reflectV.Type().AssignableTo(field.FieldType) { field.ReflectValueOf(value).Set(reflectV) } else if reflectV.Kind() == reflect.Ptr { diff --git a/tests/scanner_valuer_test.go b/tests/scanner_valuer_test.go index 632bd74a..bee0ae98 100644 --- a/tests/scanner_valuer_test.go +++ b/tests/scanner_valuer_test.go @@ -136,6 +136,8 @@ type ScannerValuerStruct struct { Strings StringsSlice Structs StructsSlice Role Role + UserID *sql.NullInt64 + User User } type EncryptedData []byte