Skip to content

Commit

Permalink
Merge pull request #1108 from j2gg0s/feat-downgrade-to-field-as-map-k…
Browse files Browse the repository at this point in the history
…ey-in-has-many

feat: downgrade to use the field in has-many-relation
  • Loading branch information
j2gg0s authored Jan 15, 2025
2 parents f5b17c3 + 91e0d27 commit dbae5e6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
18 changes: 13 additions & 5 deletions model_table_has_many.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (m *hasManyModel) Scan(src interface{}) error {

for i, f := range m.rel.JoinPKs {
if f.Name == column {
m.structKey[i] = indirectFieldValue(field.Value(m.strct))
m.structKey[i] = indirectAsKey(field.Value(m.strct))
break
}
}
Expand Down Expand Up @@ -144,19 +144,27 @@ func baseValues(model TableModel, fields []*schema.Field) map[internal.MapKey][]

func modelKey(key []interface{}, strct reflect.Value, fields []*schema.Field) []interface{} {
for _, f := range fields {
key = append(key, indirectFieldValue(f.Value(strct)))
key = append(key, indirectAsKey(f.Value(strct)))
}
return key
}

// indirectFieldValue return the field value dereferencing the pointer if necessary.
// indirectAsKey return the field value dereferencing the pointer if necessary.
// The value is then used as a map key.
func indirectFieldValue(field reflect.Value) interface{} {
func indirectAsKey(field reflect.Value) interface{} {
if field.Kind() != reflect.Ptr {
i := field.Interface()
if valuer, ok := i.(driver.Valuer); ok {
if v, err := valuer.Value(); err == nil {
return v
switch reflect.TypeOf(v).Kind() {
case reflect.Array, reflect.Chan, reflect.Func,
reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
// NOTE #1107, these types cannot be used as map key,
// let us use original logic.
return i
default:
return v
}
}
}
return i
Expand Down
2 changes: 1 addition & 1 deletion model_table_m2m.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (m *m2mModel) scanM2MColumn(column string, src interface{}) error {
if err := field.Scan(dest, src); err != nil {
return err
}
m.structKey = append(m.structKey, indirectFieldValue(dest))
m.structKey = append(m.structKey, indirectAsKey(dest))
break
}
}
Expand Down

0 comments on commit dbae5e6

Please sign in to comment.